zoukankan      html  css  js  c++  java
  • 如何处理React state更新是异步的情况下无法及时更新状态

    State 的更新可能是异步的

    出于性能考虑,React 可能会把多个 setState() 调用合并成一个调用。

    因为 this.props 和 this.state 可能会异步更新,所以你不要依赖他们的值来更新下一个状态。

    例如,此代码可能会无法更新计数器:

    // Wrong
    this.setState({
      counter: this.state.counter + this.props.increment,
    });

    要解决这个问题,可以让 setState() 接收一个函数而不是一个对象。这个函数用上一个 state 作为第一个参数,将此次更新被应用时的 props 做为第二个参数:

    // Correct
    this.setState((state, props) => ({
      counter: state.counter + props.increment
    }));

    上面使用了箭头函数,不过使用普通的函数也同样可以:

    // Correct
    this.setState(function(state, props) {
      return {
        counter: state.counter + props.increment
      };
    });
  • 相关阅读:
    java泛型
    跨域传递
    laravel的一些语法
    去重
    laravel的一些查询语句
    mysql把之前表单进行拆分
    Laravel5.1接收json数据
    thinkphp5 composer安装验证码
    关于地图经纬度的问题
    tp5分组查询
  • 原文地址:https://www.cnblogs.com/art-poet/p/13151229.html
Copyright © 2011-2022 走看看