<! DOCTYPEhtml>
<html>

<head>
    <meta charset="UTF-8" />
    <title>The state and setState of the React component</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/[email protected]/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 binding is necessary to make 'this' work in the callback
          this.handleClick = this.handleClick.bind(this);
        }
 
        handleClick() {
            console.log(this.state.isToggleOn); // The first time, both prints are false, or true
            this.setState(prevState= > ({
                isToggleOn: !prevState.isToggleOn
            }));
            console.log(this.state.isToggleOn); // Print false the second time, both times, or 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 } // The previous setState returns count 0, and the current setState returns 1
            })
            this.setState((prevState) = > {
                return { count2: prevState.count2 + 2 } // The last setState returned count 1, and the current setState returns 3})}render() {
          return (
            <button onClick={this.handleClick}>
              {this.state.isToggleOn ? 'ON' : 'OFF'}
            </button>
          );
        }
      }
 
      ReactDOM.render(
        <Toggle />.document.getElementById('root'));</script>
</body>

</html>
Copy the code