尽管异步等待,但反应状态无法及时更新以进行渲染 [英] React state not updating in time for render despite async-await
问题描述
我无法及时更新React状态以进行渲染.
I have trouble updating React state in time for render.
所有API调用都返回数据,因此一定是由于异步性引起的,但我不确定如何解决.我尝试了多次回调和垃圾邮件发送,但都无济于事.
All API calls are returning data, so it must be due to asynchronicity but I am unsure how to fix it. I tried callback and spamming await at multiple spots to no avail.
这是代码的要旨:
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
的值,因为在渲染时其值是不确定的.
Error seems to be that findAuthor is slow to return values for the array this.state.authors
, as its values are undefined at the time of render.
推荐答案
异步函数中的返回位置不正确.异步函数返回无法解决,因为已将其放置在Promise解决之后.正确的样式功能如下所示:
Return place in async function is incorrect. Async function return can't resolve because is placed after Promise resolved. The correct style function is look like this:
const findAuthor = (id) => (
new Promise((resolve) => {
API.findById(id)
.then(res => { resolve(res.data.name) })
});
);
这篇关于尽管异步等待,但反应状态无法及时更新以进行渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!