继续获得受控制的与不受控制的反应错误

时间:2017-02-02 08:22:21

标签: javascript reactjs

我一直在我的控制台中收到此错误:

  

warning.js?8a56:36警告:LoginForm正在更改受控输入   密码类型不受控制。输入元素不应该切换   从受控到不受控制(反之亦然)。决定使用   一个受控或不受控制的输入元件,用于寿命   零件。更多信息:https://facebook.github.io/react/docs/forms.html#controlled-components

我看过这些问题:

以下是组件:

export default class LoginForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      values: {
        username: "",
        password: ""
      }
    };

    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this._clearInput = this._clearInput.bind(this);
  }

  onSubmit(event) {
    // this.props.attemptLogin
    event.preventDefault();
    console.log(this.state.values);
    let {username, password} = this.state.values;

    this.props.attemptLogin(username, password)
    .then((userInfo) => {
      console.log(userInfo);
      LocalStore.setJson('api', userInfo.api);
      LocalStore.setJson('user', userInfo.user);

      this._clearInput('username' , 'password');

    })
    .catch((err) => {
      console.log("Failed:");
      console.log(err);
      this._clearInput('password');
    });
  }

  _clearInput(...fields) {
    let newValuesState = {};
    fields.forEach((field) => {
      newValuesState[field] = '';
    });
    this.setState({values: newValuesState});
  }

  onChange(event) {
    let name = event.target.name;
    let value = event.target.value;
    this.setState({values: {[name]: value}});
  }

  render() {
    return (
      <div>
        <form method="post" onSubmit={this.onSubmit}>
          <div><input type="text" name="username" onChange={this.onChange} value={this.state.values.username}/></div>
          <div><input type="password" name="password" onChange={this.onChange} value={this.state.values.password}/></div>
          <div><button type="submit">Login</button></div>
        </form>
      </div>
    );
  }
}

LoginForm.propTypes = {
  attemptLogin: React.PropTypes.func.isRequired
};

代码似乎确实有效,但是这个错误会在控制台中弹出,所以我不能继续我,直到我让它停止出现。谁能看到我在组件中做错了什么?

1 个答案:

答案 0 :(得分:1)

由于您将值嵌套在state.values中,因此您的onChange函数将删除未更改的字段。你可以这样做:

onChange(event) {
    let name = event.target.name;
    let value = event.target.value;
    let values = {...this.state.values};
    values[name] = value;
    this.setState({values}});
}