The project componentWillReceiveProps switch to getDerivedStateFromProps

  For a long period of time, life cycle functions componentWillReceiveProps is the only way to be updated after the response Props change.

  react plans 17.0 deleted componentWIllMount, componentWillReceiveProps and componentWillUpdate. Since then, only the new "UNSAFE_" life-cycle name is valid.

  It will be used in the project to replace componenetWillReceiveProps things getDerivedStateFromProps also be in progress. First put down the original method code:

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userList: [],
      editInfo: { name: "", parentId: null, managerId: "", id: "" }
    };
  }

    componentWillReceiveProps(nextProps) {
    if (this.props.editInfo.id !== nextProps.editInfo.id) {
      this.props.form.setFieldsValue({name:nextProps.editInfo.name,'user':nextProps.editInfo.managerId})
    }
  }  

}

  Official update documentation says: "and componentDidUpdate together, this new life cycle (getDerivedStateFromProps) should cover all use cases componentWillReceiveProps of old."

  getDerivedStateFromProps can get the props update, but a direct replacement came, this.props access error. You can only modify the state, and componenetDidUpdate can monitor the state before the modification. I'm here and relatively a lot, and then modify the form by form this.props. code show as below:

  static getDerivedStateFromProps(props, state) {
    if (props.editInfo.id !== state.editInfo.id) {
      return {
        editInfo: props.editInfo
      };
    }

    return null;
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.editInfo.id !== prevState.editInfo.id) {
      this.props.form.setFieldsValue({
        name: this.state.editInfo.name,
        user: this.state.editInfo.managerId
      });
    }
  }

  but! Older componentWillReceiveProps or new getDerivedStateFromProps have increased the complexity of the components, usually leads to a number of bug unexpected.

  https://zh-hans.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html

  This document has more thought for both life-cycle approach, you can reference.

Guess you like

Origin www.cnblogs.com/wlxll/p/11828286.html