简体   繁体   English

React.js表单输入onChange与getDerivedStateFromProps有问题

[英]React.js Form input onChange having issue with getDerivedStateFromProps

Input onChange not updating the state when getDerivedStateFromProps used. 输入onChange在使用getDerivedStateFromProps时不更新状态。 After I passed the props from parent to child, I'm checking through getDerivedStateFromProps from child component. 在我将道具从父级传递给子级之后,我正在检查来自子组件的getDerivedStateFromProps Full demo - https://codesandbox.io/s/011m5jwyjw 完整演示 - 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). 从React 16.4开始, getDerivedStateFromProps并在每次更新时获取组件道具,无论它是什么原因(更改道具或状态)。 So every time when you call this.setState the form values are reset by this code: 因此,每次调用this.setState时,此代码都会重置表单值:

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. 要修复它,请将当前用户保存到状态,并仅在用户更改时重置form状态属性。

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

// ...

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

  return {};
}

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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