【发布时间】:2021-09-29 07:34:01
【问题描述】:
我试图从“index.js”文件中的异步调用中获取数组。
// index.js
const loadItem = async () => {
const items = await axios.get("https://api.example.com")
.then(res => {
return res.data
})
.catch(() => {
console.log('error')
});
console.log([items]) // Array(25)
return [items]
};
loadItem()
//And want to put this result value to in initstate(to make reducer) as below.
const initState = loadItem();
function reducer(state=initState, action) {
return state
}
但是,在 App.js 页面的“console.log(props.state)”之后,我可以看到下面的结果
// App.js
Promise
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(25)
在这种情况下,我如何访问 [PromiseResult] 作为状态值?
(我想把这个 Array 值作为 initState 值 放在 'index.js' 页面中)
我希望使用这个 Array,但是我找不到访问这个 PromiseResult 状态的方法。
【问题讨论】:
-
您无法直接访问该值。你在 Promise 上使用
await或.then()从 Promise 中获取值。这是获得价值的唯一两种方法。关于 promise 的事情是,你永远不知道值何时在 promise 中,所以你使用.then()或await来获取值。如果价值已经存在,那么它们几乎会立即为您提供价值。如果该值尚不存在(承诺仍在等待中),他们会在该值存在时通知您。这就是 Promise 的工作方式。没有其他方法可以使用 Promise。 -
将初始状态设为空数组,并在承诺完成时更新它。
-
哦,我不知道在 promise 上使用“await”或“.then()”!我两个都用过!谢谢你的建议!
标签: reactjs async-await react-redux state es6-promise