React state with calculated fields

后端 未结 6 1850
半阙折子戏
半阙折子戏 2021-02-13 18:24

I have a react component, which has properties and state. Some fields of state contain input data (uplifted from input control), but there is also fields in the state that must

6条回答
  •  广开言路
    2021-02-13 19:00

    It looks like the "state" is the place to store everything (even computed values) you'll need to use on the render function, but usually we have the problem you describe.

    Since React 16.3 a new approach for this situation has been given in the way of the static getDerivedStateFromProps (nextProps, prevState) "lifecycle hook".

    You should update at least to this version if you haven't, and follow the advice given by the React Team on their blog.

    Here is the official documentation for this functionality.

    The issue here is that this function is invoked before every render, and being "static" you cannot access the current instance previous props, which is usually needed to decide if the computed value must be generated again or not (I suppose this is your case, as you have stated your computation process is heavy). In this case, the React team suggests to store in the state the values of the related props, so they can be compared with the new ones:

    if (nextProps.propToCompute !== prevState.propToComputePrevValue) {
      return {
        computedValue: Compute(nextProp.propToCompute),
        propToComputePrevValue: nextProps.propToCompute
      };
    }
    return null;
    

提交回复
热议问题