简体   繁体   中英

React.js Form input onChange having issue with getDerivedStateFromProps

Input onChange not updating the state when getDerivedStateFromProps used. After I passed the props from parent to child, I'm checking through getDerivedStateFromProps from child component. Full demo - https://codesandbox.io/s/011m5jwyjw

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {}
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.user) {
      return { form: nextProps.user };
    }

    return {
      ...prevState
    };
  }

  inputHandle(e) {
    this.setState(prevState => ({
      ...prevState,
      form: {
        firstname: e.target.value
      }
    }));
  }

  render() {
    return (
      <input
        type="text"
        name="firstname"
        value={this.state.form.firstname}
        onChange={e => this.inputHandle(e)}
      />
    );
  }
}

Starting from React 16.4, getDerivedStateFromProps is called and gets the component props on every update no matter what caused it (changing the props or the state). So every time when you call this.setState the form values are reset by this code:

if (nextProps.user) { // nextProps are here on every state change
  return { form: nextProps.user };
}

In order to fix it, save the current user to state and reset the form state attribute only when the user changes.

this.state = {
  form: {},
  lastUser: null,
};

// ...

static getDerivedStateFromProps(nextProps, prevState) {
  if (nextProps.user !== prevState.lastUser) {
    return {
      form: nextProps.user,
      lastUser: nextProps.user
    };
  }

  return {};
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM