setState()之后使用state的问题

版权声明:觉得有帮助到你的话,请在右边点个赞吧! https://blog.csdn.net/u011215669/article/details/82837934

一开始知道setState()是异步执行方法,在使用这个方法改变state之后直接用this.state获取的state不是更新之后的,只有render发生变化的时候才触发this.setState()

  constructor(props) {
    super(props)
    this.state = {
         filter: {
        type: 'day',
        time: '1919-19-13'
      }
    };
    this.onDateChange = this.onDateChange.bind(this)
  }
  onDateChange(obj, date) {
    console.log('date', date);
    this.setState({
      filter: {
        type: 'day',
        time: date
      }
    })
     this.handleSearch()
  }
  handleSearch=()=>{
  	console.log(this.state.filter)			//更新之前的1919-19-13
  }

一开始知道setState()是异步执行方法,在使用这个方法改变state之后直接用this.state获取的state不是更新之后的,只有render发生变化的时候才触发this.setState()
通过查询资料知道,setState()其实可以传入第二个参数用于回调函数,对代码作如下改进

  constructor(props) {
    super(props)
    this.state = {
         filter: {
        type: 'day',
        time: '1919-19-13'
      }
    };
    this.onDateChange = this.onDateChange.bind(this)
  }
  onDateChange(obj, date) {
    console.log('date', date);
    this.setState({
      filter: {
        type: 'day',
        time: date
      }
    },this.handleSearch())
  }
  handleSearch=()=>{
  	console.log(this.state.filter)			//依然是更新之前的1919-19-13
  }

发现问题依然存在,继续查询知道必须在第二个回调函数里再包一层函数,改进代码如下

  constructor(props) {
    super(props)
    this.state = {
         filter: {
        type: 'day',
        time: '1919-19-13'
      }
    };
    this.onDateChange = this.onDateChange.bind(this)
  }
  onDateChange(obj, date) {
    console.log('date', date);
    this.setState({
      filter: {
        type: 'day',
        time: date
      }
    },()=>  this.handleSearch())
  }
  handleSearch=()=>{
  	console.log(this.state.filter)			//输出更新后的state
  }

猜你喜欢

转载自blog.csdn.net/u011215669/article/details/82837934