class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 这个绑定是必要的,使`this`在回调中起作用
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this.state.isToggleOn); //第一次,两次打印的都是 false ,或者都是true
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
console.log(this.state.isToggleOn); //第二次,两次打印的都是 false ,或者都是true
this.setState({ count: 0 }) // => this.state.count 还是 undefined
this.setState({ count: this.state.count + 1}) // => undefined + 1 = NaN
this.setState({ count: this.state.count + 2}) // => NaN + 2 = NaN
this.setState((prevState) => {
return { count2: 0 }
})
this.setState((prevState) => {
return { count2: prevState.count2 + 1 } // 上一个 setState 的返回是 count 为 0,当前返回 1
})
this.setState((prevState) => {
return { count2: prevState.count2 + 2 } // 上一个 setState 的返回是 count 为 1,当前返回 3
})
}
render() {
return (
{this.state.isToggleOn ? 'ON' : 'OFF'}
);
}
}
ReactDOM.render(
document.getElementById('root')
);
文章来源
发表评论