Home  >  Article  >  Web Front-end  >  Detailed explanation of the use of setState in React

Detailed explanation of the use of setState in React

php中世界最好的语言
php中世界最好的语言Original
2018-05-24 14:19:008592browse

This time I will bring you a detailed explanation of the use of setState in React. What are the precautions when using setState in React? Here are practical cases, let’s take a look.

Throw a question

class Example extends Component {
  contructor () {
    super()
    this.state = {
      value: 0,
      index: 0
    }
  }
  componentDidMount () {
    this.setState({value: this.state.value + 1})
    console.log(this.state.value) // 第一次输出
    this.setState({value: this.state.value + 1})
    console.log(this.state.value) // 第二次输出
    setTimeout(() => {
      this.setState({value: this.state.value + 1})
      console.log(this.state.value) // 第三次输出
      this.setState({value: this.state.value + 1})
      console.log(this.state.value) // 第四次输出
    }, 0);
        this.refs.button.addEventListener('click', this.click)
  }
  click = () => {
    this.setState({value: this.state.index + 1})
    this.setState({value: this.state.index + 1})
  }
  render () {
    return (
      <p><span>value: {this.state.value}index: {this.props.index}</span>
        <button>点击</button>
      </p>
    )
  }
}
  • According to common sense, these four outputs are: 1, 2, 3, 4. However, the actual output is: 0, 0, 2, 3

Notes on setState

  1. setState will not immediately change the state in the React component The value of (that is, setState is an asynchronous update)

  • setState implements state update through a queue mechanism;

  • When setState is executed, The state that needs to be updated will be merged and put into the state queue instead of being updated immediately. The queue can efficiently update the state in batches;

  • If the value is directly modified through this.state, the state will not be updated immediately. Will be put into the state queue. When setState is called next time and the state queue is merged, the state that was directly modified before will be ignored.

  • setState triggers a component update process To trigger redraw

    • Redraw here refers to the update of ReactLife cycleFunction 4 functions:

    • shouldComponentUpdate (this.state is not updated when called; if false is returned, the life cycle is interrupted, and although subsequent functions are not called, the state will still be updated)

    • componentWillUpdate (this.state is not updated when called)

    • render (this.state is updated when called)

    • componentDidUpdate

  • Multiple adjacent state modifications may be merged together and executed at once

  •  this.setState({name: 'Pororo'})
     this.setState({age: 20})
    • Equal Yu

     this.setState({name: 'Pororo',age: 20})
    • The effect of the above two blocks of code is the same. If each call triggers a life cycle update, the performance will be very high. Therefore, React will put the modifications generated by multiple this.setState into a queue, and when it is almost the same, it will trigger a life cycle update.

    Problem Analysis

    • For the first two setStates:

    this.setState({value: this.state.val + 1});
    console.log(this.state.value); // 第一次输出
    this.setState({value: this.state.val + 1});
    console.log(this.state.value); // 第二次输出
    • Since setState does not immediately change the value of state in the React component, this.state.value in setState twice is the same value 0, so the output is 0 both times. Therefore value is only increased by 1.

    • In this case, can this.state be directly manipulated? For example: this.state.value=this.state.value 1;

    • This can indeed modify the status of this.state.value but it cannot cause duplication. render.

    • So, you must change this.state through the setState function set by React, thereby triggering re-rendering.

    • The two setStates in setTimeout:

    setTimeout(() => {
      this.setState({value: this.state.value + 1})
      console.log(this.state.value) // 第三次输出
      this.setState({value: this.state.value + 1})
      console.log(this.state.value) // 第四次输出
    }, 0);
    • These two times this.state The value is updated synchronously;

    • Synchronously updated: is the event processing triggered by React (for example: the event processing triggered by onClick), Calling setState will update this.state asynchronously;

    • Asynchronous update: Other setState calls will execute this.setState synchronously. "In addition" refers to: bypassing the event processing functions directly added by React through addEventListener and the asynchronous calls generated by setTimeout/setInterval.

    • Illustration of this.setState update mechanism:

    Detailed explanation of the use of setState in React

    • setState is generated every time The new state will be stored in a queue in turn, and then it will be judged based on the isBathingUpdates variable whether to update this.state directly or put it into dirtyComponent and talk about it later.

    • isBatchingUpdates defaults to false, which means setState will update this.state synchronously.

    • 但是,当React在调用事件处理函数之前就会调用batchedUpdates,这个函数会把isBatchingUpdates修改为true,造成的后果就是由React控制的事件处理过程setState不会同步更新this.state。

    同步更新(函数式setState)

    1. 如果this.setState的参数不是一个对象而是一个函数时,这个函数会接收到两个参数,第一个是当前的state值,第二个是当前的props,这个函数应该返回一个对象,这个对象代表想要对this.state的更改;

    2. 换句话说,之前你想给this.setState传递什么对象参数,在这种函数里就返回什么对象。不过,计算这个对象的方法有些改变,不再依赖于this.state,而是依赖于输入参数state。

    function increment(state, props) {
      return {count: state.count + 1};
    }
    function incrementMultiple() {
      this.setState(increment);
      this.setState(increment);
      this.setState(increment);
    }
    • 假如当前this.state.count的值是0,第一次调用this.setState(increment),传给increment的state参数是0,第二调用时,state参数是1,第三次调用是,参数是2,最终incrementMultiple让this.state.count变成了3。

    • 对于多次调用函数式setState的情况,React会保证调用每次increment时,state都已经合并了之前的状态修改结果。

    要注意的是,在increment函数被调用时,this.state并没有被改变,依然,要等到render函数被重新执行时(或者shouldComponentUpdate函数返回false之后)才被改变。

    同步异步setState的用法混合

    function incrementMultiple() {
      this.setState(increment);
      this.setState(increment);
      this.setState({count: this.state.count + 1});
      this.setState(increment);
    }
    • 在几个函数式setState调用中插入一个传统式setState调用,最后得到的结果是让this.state.count增加了2,而不是增加4。

    • 这是因为React会依次合并所有setState产生的效果,虽然前两个函数式setState调用产生的效果是count加2,但是中间出现一个传统式setState调用,一下子强行把积攒的效果清空,用count加1取代。

    • 所以,传统式setState与函数式setState一定不要混用。

    相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

    推荐阅读:

    JS中使用接口步骤详解

    EasyCanvas绘图库在Pixeler项目开发中使用实战总结

    The above is the detailed content of Detailed explanation of the use of setState in React. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn