React state with calculated fields

后端 未结 6 1848
半阙折子戏
半阙折子戏 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条回答
  •  -上瘾入骨i
    2021-02-13 18:47

    You can save calculated result in this.calculated instead of this.state. It is dependent data. All data which causes update and render is already in state and props.

    class Component extends React.Component {
      constructor(props) {
        super(props)
        state = {
          b: 0
        }
      }
    
      updateThis = (event) => {
        this.setState({ b: event.target.value });
      }
    
      componentWillUpdate(nextProps,nextState){
        this.calculated.field1=f(nextProps.a, nextState.b)
      }
    
      render() {
        return (
          
    A =
    B =
    f(A,B) = {this.calculated.field1}
    ); } } class ParentComponent extends React.Component { constructor(props) { super(props) state = { a: 0 } } render() { return ( this.setState({a: event.target.value})} a={this.state.a} /> } } }

提交回复
热议问题