How does a redux connected component know when to re-render?

后端 未结 4 1882
逝去的感伤
逝去的感伤 2020-12-07 07:49

I\'m probably missing something very obvious and would like to clear myself.

Here\'s my understanding.
In a naive react component, we have states &

4条回答
  •  旧时难觅i
    2020-12-07 08:36

    This answer is a summary of Brian Vaughn's article entitled You Probably Don't Need Derived State (June 07, 2018).

    Deriving state from props is an anti-pattern in all its forms. Including using the older componentWillReceiveProps and the newer getDerivedStateFromProps.

    Instead of deriving state from props, consider the following solutions.

    Two best practice recommendations

    Recommendation 1. Fully controlled component
    function EmailInput(props) {
      return ;
    }
    
    Recommendation 2. Fully uncontrolled component with a key
    // parent class
    class EmailInput extends Component {
      state = { email: this.props.defaultEmail };
    
      handleChange = event => {
        this.setState({ email: event.target.value });
      };
    
      render() {
        return ;
      }
    }
    
    // child instance
    
    

    Two alternatives if, for whatever reason, the recommendations don't work for your situation.

    Alternative 1: Reset uncontrolled component with an ID prop
    class EmailInput extends Component {
      state = {
        email: this.props.defaultEmail,
        prevPropsUserID: this.props.userID
      };
    
      static getDerivedStateFromProps(props, state) {
        // Any time the current user changes,
        // Reset any parts of state that are tied to that user.
        // In this simple example, that's just the email.
        if (props.userID !== state.prevPropsUserID) {
          return {
            prevPropsUserID: props.userID,
            email: props.defaultEmail
          };
        }
        return null;
      }
    
      // ...
    }
    
    Alternative 2: Reset uncontrolled component with an instance method
    class EmailInput extends Component {
      state = {
        email: this.props.defaultEmail
      };
    
      resetEmailForNewUser(newEmail) {
        this.setState({ email: newEmail });
      }
    
      // ...
    }
    

提交回复
热议问题