javascript - 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在数据被获取之前就返回了吗?如果是这样,那么如何正确返回值?
如果我在这里使用一些状态,那么在更新状态后它将重新渲染导致循环。所以,我认为更新状态在这里可能不是一个选项。
解决方案
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.
推荐阅读
- python - 仅替换包含字母数字、字符串和数值的列中的数值?
- html - 输入复选框在 div 中不可点击
- python - 为什么在尝试从 api 获取数据时出现此错误“TypeError:字符串索引必须是整数”?
- sql-server - 多个 CSV,一个结构 -> 使用 SSIS 的多个表
- c - 捕获信号时强制终端不打印 Ctrl 热键
- apache-spark - 如果找到匹配项,则在 master 中插入增量记录并更新现有列值
- forms - vue表单中如何预填充数据?
- deeplearning4j - DL4j 1.0.0-M1.1 在 CUDA 上运行非常慢
- powershell - 如何在powershell中将电话号码附加到国家代码
- php - WordPress 编码错误:未清理的输入变量