首页 > 解决方案 > Axios 没有按预期返回数据

问题描述

我正在学习 ReactJS。我正在尝试从天气 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在数据被获取之前就返回了吗?如果是这样,那么如何正确返回值?

如果我在这里使用一些状态,那么在更新状态后它将重新渲染导致循环。所以,我认为更新状态在这里可能不是一个选项。

标签: javascriptreactjsaxios

解决方案


Promisepending最初是返回状态。它有作为 then 的成功回调和作为 catch 的错误回调。

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说,

Promise 处于以下状态之一:

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

在此处输入图像描述


推荐阅读