【问题标题】:React state not updating in time for render despite async-await尽管 async-await,React 状态没有及时更新以进行渲染
【发布时间】: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


【解决方案1】:

异步函数中的返回位置不正确。异步函数返回无法解析,因为它放置在 Promise 解析之后。 正确的样式函数如下所示:

const findAuthor = (id) => (
  new Promise((resolve) => {
    API.findById(id)
      .then(res => { resolve(res.data.name) })
  });
);

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 2020-03-08
    • 2020-06-21
    • 2021-08-06
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多