React.js表单输入onChange遇到getDerivedStateFromProps问题

时间:2018-08-23 06:13:38

标签: javascript reactjs

使用onChange时,输入getDerivedStateFromProps不会更新状态。在将道具从父级传递到子级之后,我正在从子级组件中通过getDerivedStateFromProps进行检查。完整演示-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)}
      />
    );
  }
}

1 个答案:

答案 0 :(得分:1)

从React 16.4开始,调用SELECT NormalCol1, NormalCol2, col1 = col1_0, col2 = col2_0 FROM YourTable UNION ALL SELECT NormalCol1, NormalCol2, col1 = col1_1, col2 = col2_1 FROM YourTable UNION ALL SELECT NormalCol1, NormalCol2, col1 = col1_2, col2 = col2_2 FROM YourTable SELECT NormalCol1, NormalCol2, col1, col2 FROM YourTable CROSS APPLY ( SELECT col1 = col1_0, col2 = col2_0 UNION ALL SELECT col1 = col1_1, col2 = col2_1 UNION ALL SELECT col1 = col1_2, col2 = col2_2 ) a SELECT NormalCol1, NormalCol2, col1, col2 FROM YourTable CROSS APPLY ( VALUES (col1_0, col2_0), (col1_1, col2_1), (col1_2, col2_2) ) c (col1, col2) 并在每次更新时获取组件prop(无论是什么原因引起的(更改prop或状态))。因此,每次调用getDerivedStateFromProps时,此代码都会重置表单值:

this.setState

要修复此问题,请仅在用户更改时将当前用户保存为状态,并重置if (nextProps.user) { // nextProps are here on every state change return { form: nextProps.user }; } 状态属性。

form

Demo