zoukankan      html  css  js  c++  java
  • react--setState使用

    (一)使用注意事项

      1,不要直接修改state

      2,state的更新可能是异步的(出于性能考虑,React 可能会把多个 setState() 调用合并成一个调用,因为 this.props 和 this.state 可能会异步更新,所以你不要依赖他们的值来更新下一个状态。)

      3,state的更新会被合并(当你调用 setState() 的时候,React 会把你提供的对象合并到当前的 state。)

    (二)react异步更新带来的问题解决方案

      1,当需要在state的一些状态来改变之后做一些事情时,由于会出现异步更新会很麻烦

        1---传入回调函数

      
    setState({
        index: 1
    }}, function(){
        console.log(this.state.index);
    })
    

      2---通过es6的async和await解决

      async函数返回一个 Promise 对象,可以使用then方法添加回调函数。当函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体内后面的语句

    (三)setState的另一种使用方式(需要使用上一次的state值)

    在setState的第一个参数中传入function,该function会被压入调用栈中,在state真正改变后,按顺序回调栈里面的function。该function的第一个参数为上一次更新后的state。这样就能确保你下一次的操作拿到的是你预期的值

    class Com extends React.Component{
        constructor(props){
            super(props);
            this.state = {
                index: 0
            }
            this.add = this.add.bind(this);
        }
    
        add(){
            this.setState(prevState => {
                return {index: prevState.index + 1};
            });
            this.setState(prevState => {
                return {index: prevState.index + 1};
            });
        }
    }
  • 相关阅读:
    mysql的存储过程
    一份php高级工程师的面试题,我每天看一点点
    php的常用函数(持续更新)
    php 中文字符串截取
    php递归遍历文件目录
    ajax timeout 断网处理
    angular 刷新问题
    angular state中templateUrl 路径的模板
    angular请求传递不了数据
    截取字符串 substring substr slice
  • 原文地址:https://www.cnblogs.com/dglblog/p/10554959.html
Copyright © 2011-2022 走看看