Why there is no async getState function in React ?
文档告诉我们setState是异步的 . 很好,但这意味着 we can't safely use this.state 我们需要一个异步getState来尊重执行顺序 .
根据我的理解,我们永远不应该使用this.state并使用这样的getState函数:
getState(callback) {
this.setState((prevState) => {
callback(prevState) ;
});
}
...
this.getState((curState) => {
// we now can use the current state safely
}
在我的思维方式中,我在这里缺少什么?为什么React中不存在这样的功能?
-- EDIT --
正如我的一位朋友告诉我的那样,目前尚不清楚,因为我不相信第一个答案,让我们分析一些代码:
simpleFunc() {
setState({ "counter" : 1 });
setState({ "counter" : 2 });
this.state.counter // => no garanty about the value
getState((curState) => { // ensure curState.counter is 2 });
}
这个简单