反应功能组件中的受控组件错误

时间:2019-10-03 16:31:05

标签: javascript reactjs

我在React中使用表单,这是第一次使用功能组件。我要么发疯,要么应该没有问题...

import React, {useEffect, useState} from 'react';

function ChangePasswordComponent(props) {

  const {onChangePassword} = props;
  const [isValid, setIsValid] = useState(true);
  const [form, setForm] = useState({
    password: undefined,
    confirm: undefined
  })

  useEffect(() => {
    handleValidation();
  }, [form])

  function handleValidation() {
    setIsValid(form.password === form.confirm);
  }

  function onFormValueChanges(event) {
    setForm({...form, [event.target.name]: event.target.value})
  }

  function resetFields() {
    setForm({
      password: undefined,
      confirm: undefined
    })
  }

  function onUpdateClick() {
    onChangePassword(form.password);
    resetFields();
  }

  return (
    <div className="change-password-container">
      <input
        type="text"
        name="password"
        value={form.password}
        onChange={(event) => onFormValueChanges(event)}
        placeholder="new password" />
      <input
        type="text"
        name="confirm"
        value={form.confirm}
        onChange={(event) => onFormValueChanges(event)}
        placeholder="confirm new password" />
      {!isValid ? 
        <span className="validation-error">passwords do not match</span> : null }
      <div className="button-container">
        <button onClick={() => resetFields()}>Cancel</button>
        <button onClick={() => onUpdateClick()}
          disabled={!form.password || !isValid}>Update</button>
      </div>
    </div>
  );

}

export default ChangePasswordComponent;

但是,当我运行代码时,在控制台中出现关于...的错误

  

一个组件正在更改要控制的文本类型的不受控制的输入。输入元素不应从不受控制切换为受控制(反之亦然)。在组件的使用寿命中决定使用受控还是不受控制的输入元素。

当我回顾文档时,我的模式似乎很好地遵循了文档。有想法吗?

1 个答案:

答案 0 :(得分:2)

您应该使用''之类的空字符串代替未定义的字符串。

首次渲染组件时,密码和确认值为undefined。这意味着没有变量可以设置输入的value属性。 因此,会发生该错误。