ReactJS - Does render get called any time “setState” is called?

后端 未结 7 1057
攒了一身酷
攒了一身酷 2020-11-22 14:51

Does React re-render all components and sub components every time setState() is called?

If so, why? I thought the idea was that React only rendered as li

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 15:17

    Another reason for "lost update" can be the next:

    • If the static getDerivedStateFromProps is defined then it is rerun in every update process according to official documentation https://reactjs.org/docs/react-component.html#updating.
    • so if that state value comes from props at the beginning it is overwrite in every update.

    If it is the problem then U can avoid setting the state during update, you should check the state parameter value like this

    static getDerivedStateFromProps(props: TimeCorrectionProps, state: TimeCorrectionState): TimeCorrectionState {
       return state ? state : {disable: false, timeCorrection: props.timeCorrection};
    }
    

    Another solution is add a initialized property to state, and set it up in the first time (if the state is initialized to non null value.)

提交回复
热议问题