React 组件的 state 和 setState
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 组件的 state 和 setState</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
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 (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
</script>
</body>
</html>