我在ReactJs的Context Api中创建了temp变量。我创建了在上下文中更新其状态的函数,每当我在子级中调用该函数时,状态都不会立即更改,我必须单击两次按钮来更新州。 上下文APi代码段
setStateSynchronous=(stateUpdate)=>
{
return new Promise(resolve => {
this.setState(stateUpdate, () => resolve());
});
}
儿童代码段
async foo() {
await this.setStateSynchronous(state => ({tempVariable:state.tempVariable+65}));
// execution will only resume here once state has been applied
console.log(this.state.tempVariable); // output will be 1
}