React state with calculated fields

后端 未结 6 1863
半阙折子戏
半阙折子戏 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 18:56

    You're first attempt is the right way to solve this problem. However, you need to add a check to see if state has actually changed:

    componentDidUpdate(prevProps, prevState){
        if(prevState.field !== this.state.field){
            this.setState({calculatedField:calculate(this.props,this.state)})) 
        }
    }
    
    shouldComponentUpdate(nextProps, nextState) {
        return this.state.calculatedField !== nextState.calculatedField
    }
    

    You need to check the pieces of state and props that you use in your calculate method and make sure they have changed before updating state again. This will prevent the infinite loop.

提交回复
热议问题