【发布时间】:2020-03-30 06:41:38
【问题描述】:
我无法及时更新 React 状态以进行渲染。
所有 API 调用都在返回数据,所以这一定是由于异步性,但我不确定如何修复它。我在多个地方尝试了回调和垃圾邮件等待都无济于事。
这里是代码的要点:
findAuthor = async (id) => { // takes an ID and returns a name
await API.findById(id)
.then(res => { return res.data.name })
}
getPosts = async () => {
await API.getPosts({})
.then(posts =>
{ let authorIds = [];
(async () => {
for (let obj of posts.data) {
await authorIds.push(obj.author); // collect IDs
}
for (let id of authorIds) {
let val = this.findAuthor(id); // query for names using the collected IDs
await names.push(val);
}
await this.setState({ authors: names }) // update state
})() // End of immediately invoked function
}
)
}
render() {
return (
<div>
{this.state.authors.length > 0
? this.state.someOtherArray.map(function (item, index) {
return <Card
key={index}
displayName={this.state.authors[index]} // says the value is undefined
/>
})
: <p> No data </p>
}
</div>
)}
错误似乎是 findAuthor 返回数组 this.state.authors 的值很慢,因为它的值在渲染时未定义。
【问题讨论】:
-
使用代码沙箱提供此代码
-
这个
someOtherArray在哪里,你为什么要依赖someOtherArray来迭代this.state.authors? -
你的 this.findAuthor(id) 不会返回一个承诺吗?您必须使用 Promise.all() 来解决它们?
标签: javascript node.js reactjs asynchronous async-await