2 回答

TA貢獻1936條經驗 獲得超7個贊
您可以將回調傳遞給 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 可能會批量更新狀態。

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
}
}
添加回答
舉報