Hir*_*oki 0 reactjs react-native
我想知道this.setState改变是否立即出现,因为它似乎没有这样做.
为了说明,我们假设有一个复选框....
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
switch: false
};
this.switch = this.switch.bind(this);
}
clickCoverSwitch(){
console.log("Before clicking - ", this.state.switch);
this.setState({switch: !this.state.switch});
console.log("Now, the state is - ", this.state.switch);
}
render() {
return (
<input onClick={this.clickCoverSwitch} defaultChecked={this.state.coverSwitch} type="checkbox">
</input>
);
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,默认情况下该复选框处于关闭状态 - 这是正常的.
但是,单击开关(即复选框)时,我在控制台中看到以下消息.
Before clicking - false
Now, the state is - false
应该显示第二行true,因为this.state.switch应该已经改变了this.setState({switch: !this.state.switch}).
我不确定我应该怎么解释这一点.任何建议将被认真考虑!
setState()不会立即改变this.state,但会创建挂起状态转换.调用此方法后访问this.state可能会返回现有值.
根据以前的状态值更改状态时,最好使用以下语法:
this.setState((prevState) => ({ switch: !prevState.switch}));
Run Code Online (Sandbox Code Playgroud)
这样,如果有多个挂起状态更改,它们将不会相互覆盖:
//This way leads to undesirable results
Somefunction() {
this.setState({ counter: this.state.counter + 3})
this.setState({ counter: this.state.counter + 5})
}
//this.state.counter === 5 here
betterfunction() {
this.setState((prevState) => ({ counter: prevState.counter + 3}))
this.setState((prevState) => ({ counter: prevState.counter + 5}))
}
//The second setState will change based on the first one's values instead of overwritting them
//this.state.counter === 8 here
Run Code Online (Sandbox Code Playgroud)
更多信息:https://facebook.github.io/react/docs/react-component.html#setstate
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |