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
      }
    
  • 相关阅读:
    2021.2.28
    《构建之法》11~16章读后感
    《构建之法》6~10章读后感
    《构建之法》1~5章读后感
    4.7 wait notify
    4.8 wait,notify 的正确姿势
    4.9 park&unpark
    4.10 重新理解线程的状态转换
    第七章 Redis-6.2.1脚本安装
    第三十九章 Centos 7 系统优化脚本
  • 原文地址:https://www.cnblogs.com/YooHoeh/p/9756244.html
Copyright © 2011-2022 走看看