Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 尽管异步等待,但未及时更新呈现的反应状态_Javascript_Node.js_Reactjs_Asynchronous_Async Await - Fatal编程技术网

Javascript 尽管异步等待,但未及时更新呈现的反应状态

Javascript 尽管异步等待,但未及时更新呈现的反应状态,javascript,node.js,reactjs,asynchronous,async-await,Javascript,Node.js,Reactjs,Asynchronous,Async Await,我无法及时更新React状态以进行渲染 所有API调用都返回数据,所以这一定是由于异步性造成的,但我不确定如何修复它。我试着在多个地点回拨和发送垃圾邮件等待,但都没有用 以下是守则的要点: findAuthor = async (id) => { // takes an ID and returns a name await API.findById(id) .then(res => { return res.data.name }) } render(){ 返回(

我无法及时更新React状态以进行渲染

所有API调用都返回数据,所以这一定是由于异步性造成的,但我不确定如何修复它。我试着在多个地点回拨和发送垃圾邮件等待,但都没有用

以下是守则的要点:

findAuthor = async (id) => {   // takes an ID and returns a name
  await API.findById(id)
    .then(res => { return res.data.name })
}
render(){
返回(
{this.state.authors.length>0
?this.state.someOtherArray.map(函数(项、索引){
返回
})
:没有数据

} )}

错误似乎是FinDautor为数组返回值的速度较慢,因为它的值在渲染时未定义。

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

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

使用代码沙盒提供此代码此
someOtherArray
在哪里?您为什么依赖
someOtherArray
来迭代
此.state.authors
?您的this.findautor(id)不会返回承诺吗?您必须使用Promise.all()来解决这些问题?
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>
)}
const findAuthor = (id) => (
  new Promise((resolve) => {
    API.findById(id)
      .then(res => { resolve(res.data.name) })
  });
);