axios未按预期返回数据

gab6jxml  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(256)

我在学英语。我正在尝试从weather api获取数据,但当我登录组件时,我得到了以下信息:

Promise{<pending>}
__proto__: Promise
{[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object}

但是当我登录到 .then 然后我成功地获取了所有数据。我正在附上我的密码。

const App = () => {
const weatherData =  (capital) =>  axios.get(`http://api.weatherstack.com/current?access_key=${process.env.REACT_APP_API_KEY}&query=${capital}`)
  .then(response => {
    console.log(response.data.current) // getting expected data
    return (response.data.current)
  })

<IndividualCountry weatherData={weatherData(countriesShow[0].capital)} />
}

const IndividualCountry = ({weatherData}) => {
  console.log('here', weatherData)  // Getting weird logs
  return()
}

我忽略了其他事情。那么,为什么会发生这种情况?是否因为promise在获取数据之前返回?如果是这样,那么如何正确返回值?
如果我在这里使用一些状态,那么在更新状态之后,它将重新渲染,这将导致循环。所以,我认为在这里更新状态可能不是一个选项。

cld4siwp

cld4siwp1#

承诺就是回报 pending 最初陈述。它有成功回调和错误回调。

const App = () => {

const weatherData =  async (capital) =>  await axios.get(`http://api.weatherstack.com/current?access_key=${process.env.REACT_APP_API_KEY}&query=${capital}`)

<IndividualCountry weatherData={weatherData(countriesShow[0].capital)} />
}

const IndividualCountry = ({weatherData}) => {
  console.log('here', weatherData)  // you will get data here
  return()
}

mdn说,
承诺在以下状态之一:

pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.

g6ll5ycj

g6ll5ycj2#

你试过了吗 async 像这样等待:

const App = () => {
const weatherData =  async (capital) =>  {
    axios.get(`http://api.weatherstack.com/current?access_key=${process.env.REACT_APP_API_KEY}&query=${capital}`)
console.log(data) 
} 

.......

或者尝试使用 useEffect()

useEffect(async () =>{
const { data } =await axios.get(`http://api.weatherstack.com/current?access_key=${process.env.REACT_APP_API_KEY}&query=${capital}`)

console.log(data)
}, [capital] )

还要确保通过尝试

console.log(`http://api.weatherstack.com/current?access_key=${process.env.REACT_APP_API_KEY}&query=${capital}`)

从控制台抓取url,然后将其粘贴到浏览器上,以查看是否得到结果。
然后尝试调用该函数,看看是否仍然得到相同的结果

相关问题