[英]React state not updating in time for render despite async-await
我無法及時更新 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
值很慢,因為它的值在渲染時未定義。
異步函數中的返回位置不正確。 異步函數返回無法解析,因為放置在 Promise 解析之后。 正確的樣式函數如下所示:
const findAuthor = (id) => (
new Promise((resolve) => {
API.findById(id)
.then(res => { resolve(res.data.name) })
});
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.