Javascript 异步循环问题中的React if语句
救命啊,我似乎想不出如何解决这个问题:Javascript 异步循环问题中的React if语句,javascript,reactjs,asynchronous,axios,Javascript,Reactjs,Asynchronous,Axios,救命啊,我似乎想不出如何解决这个问题: array.map(object => { console.log(this.state.newArr) // [] didn't update despite setState if (this.state.newArr.length === 0) { axios.get('http://localhost/') .then(res => { this.setState(prevState
array.map(object => {
console.log(this.state.newArr) // [] didn't update despite setState
if (this.state.newArr.length === 0) {
axios.get('http://localhost/')
.then(res => {
this.setState(prevState => ({ newArr: [...prevState.newArr, res] })) // setState here
})
}
})
编辑:更新的代码实现了答案,但仍然不起作用。异步/等待模式可以是一个解决方案。从未在地图上尝试过,但会是这样:
array.map(async object => {
if (this.state.newArr.length === 0) {
const response = await axios.get('http://localhost/');
await this.setStateAsync({ newArr: [...this.state.newArr, response] });
// or without the setStateAsync
// this.setState(prevState => ({ newArr: [...prevState.newArr, response] }));
}
});
const setStateAsync = state => {
return new Promise((resolve) => {
this.setState(state, resolve)
});
}
是,这意味着在循环中设置状态时,您还没有更新的状态值。基于以前的状态值进行状态更新时,应使用setState的更新程序形式
出了什么问题的例子
类示例扩展了React.Component{
建造师{
超级的
此.state={
arr:[]
}
}
组件安装{
[1,2,3]。forEachi=>{
//setState是异步的,
//所以它没有被下一个循环更新
//意思是每个周期都是一样的
console.logthis.state.arr
this.setState{arr:[…this.state.arr,i]};
}
}
渲染{
//数组中只有最后一个enty
console.log'final',this.state.arr
回归试验;
}
}
ReactDOM.render,document.getElementById'root'
我们需要更多的背景。这个循环位于哪里?它位于componentDidMount中,我所说的循环是映射函数。componentDidMount只运行一次。更新状态后,它不会再次运行。是的,我知道,但它至少应该完成映射循环,对吗?确实如此,但setState是异步的,因此它在设置时不会使用更新的值。我将用一个示例来回答Updater表单很好,但我认为它不会单独回答这个问题。axios请求不会等待,因此状态更新,即使使用更新表单,也不会同步。哦,你是对的,在使用新的prevState进行测试之后。这仍然没有解决axios的问题:sorry@ErisSuryaputraSetStateAAsync是否正常工作?如果是,那么我将删除我以前的UpdateNode,我认为它以前工作过,但不幸的是它仍然不起作用。如果你不打算使用传入的prevState,那么使用updater没有任何好处。@Brianthonpson谢谢你,我也忘了更改它。编辑: