我无法及时更新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
的值,因为在渲染时其值是不确定的。
答案 0 :(得分:0)
异步函数中的返回位置不正确。异步函数返回无法解决,因为已在Promise解决之后放置。 正确的样式功能如下所示:
const findAuthor = (id) => (
new Promise((resolve) => {
API.findById(id)
.then(res => { resolve(res.data.name) })
});
);