我知道React可以异步和批量执行状态更新,以优化性能.因此,在调用setState
之后,您永远不能相信状态会被更新.但你能相信我对update the state in the same order as 100 is called的react 吗
- 同一个组件?
- 不同的组件?
考虑单击以下示例中的按钮:
1..a is false and b is true是否有可能:
class Container extends React.Component {
constructor(props) {
super(props);
this.state = { a: false, b: false };
}
render() {
return <Button onClick={this.handleClick}/>
}
handleClick = () => {
this.setState({ a: true });
this.setState({ b: true });
}
}
2..a is false and b is true是否有可能:
class SuperContainer extends React.Component {
constructor(props) {
super(props);
this.state = { a: false };
}
render() {
return <Container setParentState={this.setState.bind(this)}/>
}
}
class Container extends React.Component {
constructor(props) {
super(props);
this.state = { b: false };
}
render() {
return <Button onClick={this.handleClick}/>
}
handleClick = () => {
this.props.setParentState({ a: true });
this.setState({ b: true });
}
}
请记住,这些都是对我的用例的极端简化.我意识到我可以用不同的方式来实现这一点,例如,在示例1中同时更新两个状态参数,以及在示例2中对第一个状态更新的回调中执行第二个状态更新.然而,这不是我的问题,我只感兴趣的是,是否有一种定义良好的方式来执行这些状态更新,而不是别的.
任何有文档支持的答案都将不胜感激.