zoukankan      html  css  js  c++  java
  • setState()之后使用state的问题

    一开始知道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
      }
    
  • 相关阅读:
    第十四周总结
    第十三周总结
    第十一周学习总结
    《软件需求》 阅读笔记
    第十周总结
    Echarts基础
    HTML中form表单text填写内容时的约束
    代码整洁之道 阅读笔记五
    pandas中的None和NaN
    pandas中的replace用法
  • 原文地址:https://www.cnblogs.com/YooHoeh/p/9756244.html
Copyright © 2011-2022 走看看