如何使用react中的回调函数消除setState中的滞后
尝试使用回调,但仍然处于滞后状态,并且无法映射处于数组状态的数据
mapfn(){
ServerAddr.get(`/dishes/read/meal/category`)
.then(res => {
const getmeal6 = res['data']['data'];
this.setState({ getmeal6 },()=>{
console.log('log233',this.state.getmeal6);
});
});
console.log('log232',this.state.getmeal6);
this.state.getmeal6.map((item) => {
return (
this.setState({
maparr:[...this.state.maparr,item.id],
})
);
});
console.log(this.state.maparr,'val32');
}```
in log233 the state is proper but in log232 the state lags with 1
答案 0 :(得分:2)
当前代码的问题是http调用和对setState
的调用都是异步的。
// this call is asynchronous
ServerAddr.get(`/dishes/read/meal/category`)
.then(res => {
const getmeal6 = res['data']['data'];
// this is also asynchronous
this.setState({ getmeal6 },()=>{
});
});
// this call happens synchronously! It will almost certainly happen before the two
// async calls complete
this.state.getmeal6.map((item) => {
return (
this.setState({
maparr:[...this.state.maparr,item.id],
})
);
});
如果要在解析HTTP调用和setState之后都要做某事,则需要位于promise的then
函数内部,或者位于setState
的回调函数中。 / p>
是这样的:
// this call is asynchronous
ServerAddr.get(`/dishes/read/meal/category`)
.then(res => {
const getmeal6 = res['data']['data'];
// this is also asynchronous
this.setState({ getmeal6 },()=>{
// this is where you need to put the
// code you want to happen after the http call and setState
});
});
也就是说,您需要重新考虑要执行的操作-通过使用Redux
之类的方法重构状态管理,或者通过在方法中使用async await
来使代码变一点更容易阅读,或者通过全新的方法解决当前的问题。