反应-复选框输入未正确更新(由于浅合并)

时间:2018-12-18 22:06:47

标签: javascript reactjs

我相信我的代码由于浅层合并而出现一些错误,尤其是我的复选框异常,因为它表现得很奇怪。有人可以建议一些解决方法吗?

这是我设置状态以及处理输入更改的方式:

state = {
  form: {
    firstName: "",
    lastName: "",
    email: "",
    password: "",
    rememberMe: false
  }
};

  handleChange = e => {
    const { name, value, checked } = e.target;
    const isCheckbox = checked === "checkbox";
    this.setState(prevState => ({
      form: {
        // all other key value pairs of form object
        ...prevState.form,

        // update this one specifically
        [name]: isCheckbox ? checked : value
      }
    }));
  };

提交并验证

  validateForm = () => {
    const formInputs = ["firstName", "lastName", "email", "password", "rememberMe"];

    for (let i = 0; i < formInputs.length; i++) {
      const inputName = formInputs[i];

      if (!this.state.form[inputName].length) {
        return false;
      }
    }

    return true;
  };

  handleSubmit = () => {
    if (this.validateForm()) {
      console.log("Success!");
      console.log(this.state);
    } else {
      console.log("Failure!");
    }
  };

这是我的表单的摘录:

   <form
      className="Form"
      onSubmit={e => {
        e.preventDefault();
        this.handleSubmit();
      }}
    >
      <input name="firstName" onChange={this.handleChange} />
      <input name="lastName" onChange={this.handleChange} />
      <input name="email" onChange={this.handleChange} />
      <input name="password" onChange={this.handleChange} />
      <input
        name="rememberMe"
        type="checkbox"
        checked={this.state.form.rememberMe}
        onChange={this.handleChange}
      />
      <button className="no-padding">Submit</button>
    </form>

提交后设法获得“成功”,但是我的复选框异常,并且保持选中状态。

1 个答案:

答案 0 :(得分:2)

我认为应该是

 const { name, value, checked, type } = e.target;
 const isCheckbox = type === "checkbox";

 const { name, value, checked } = e.target;
     const isCheckbox = name === "rememberMe";