React state with calculated fields

后端 未结 6 1845
半阙折子戏
半阙折子戏 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:51

    I wouldn't advice you to store your calculated value inside your state. My approach would be more like this:

    import PropTypes from 'prop-types';
    import React from 'react';
    
    class Component extends React.Component {
      static defaultProps = { value: 0 };
    
      static propTypes = { value: PropTypes.number };
    
      state = { a: 0, b: 0 };
    
      result = () => this.state.a + this.state.b + this.props.value;
    
      updateA = e => this.setState({ a: +e.target.value });
    
      updateB = e => this.setState({ b: +e.target.value });
    
      render() {
        return (
          
    A: B: Result: {this.result()}
    ); } }

    The problem with storing the calculation inside your state is, that the calculation can be mutated by multiple sources. If you use my solution, there is no way, that anything can overwrite the calculation WITHOUT using the correct function to calculate them.

提交回复
热议问题