天天看点

React中的setState是异步的,第二个参数为回调函数

以下举个简单的例子:点击修改state中的num

import React, { Component } from 'react';

class Pratice extends Component {
    constructor(props) {
        super(props)
        this.state = {
            num: 1
        }
    }
    render() {
        return (
            <div>
            	<tag onClick={this.handleClick.bind(this)}></tag>
            </div>
        );
    }
    // 每个选项点击后执行的代码
    handleClick(title, index) {
        this.setState({
          num: 2
        });
      	console.log(this.state.num);	// 这里打印出来是1
    }
}
export default Pratice;
           

因为setState是异步的,以上代码如果需要正常打印出2,需要把执行代码写入setState的回调函数内

handleClick(title, index) {
  this.setState({
    num: 2
  }, ()=>{
    console.log(this.state.num);	// 这里打印出来是2
  });
}