Javascript 尽管异步等待,但未及时更新呈现的反应状态
我无法及时更新React状态以进行渲染 所有API调用都返回数据,所以这一定是由于异步性造成的,但我不确定如何修复它。我试着在多个地点回拨和发送垃圾邮件等待,但都没有用 以下是守则的要点: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(){ 返回(
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) })
});
);