2 回答
![?](http://img1.sycdn.imooc.com/545845e900013e3e02200220-100-100.jpg)
TA贡献1936条经验 获得超6个赞
您可以将回调传递给 setState。
this.setState(
(state, props) => ({showLabelDetails : !state.showLabelDetails}),
() => { // Executed when state has been updated
// Do stuff with new state
if (this.state.showLabelDetails) {
this.setState({ labelDetails: {} })
}
}
)
顺便说一句:你不能依赖 setState 中的 this.state (在 react 文档中提到),因为 react 可能会批量更新状态。
![?](http://img1.sycdn.imooc.com/533e52b90001456f02000200-100-100.jpg)
TA贡献1806条经验 获得超8个赞
你可以尝试做这样的事情:
class MyComponent extends Component {
function setStateSynchronous(stateUpdate) {
return new Promise(resolve => {
this.setState(stateUpdate, () => resolve());
});
}
async function foo() {
// state.count has value of 0
await setStateSynchronous(state => ({count: state.count+1}));
// execution will only resume here once state has been applied
console.log(this.state.count); // output will be 1
}
}
添加回答
举报