setState doesn't update the state immediately

前端 未结 12 2489
暖寄归人
暖寄归人 2020-11-21 05:25

I would like to ask why my state is not changing when I do an onclick event. I\'ve search a while ago that I need to bind the onclick function in constructor but still the s

12条回答
  •  天涯浪人
    2020-11-21 05:40

    setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

    setState() will always lead to a re-render unless shouldComponentUpdate() returns false. If mutable objects are being used and conditional rendering logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

    The first argument is an updater function with the signature:

    (state, props) => stateChange
    

    state is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props. For instance, suppose we wanted to increment a value in state by props.step:

    this.setState((state, props) => {
        return {counter: state.counter + props.step};
    });
    

提交回复
热议问题