【问题标题】:React controlled component error in function component功能组件中的反应受控组件错误
【发布时间】:2019-10-03 16:31:05
【问题描述】:

我正在使用 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;

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

组件正在更改要控制的文本类型的不受控制的输入。输入元素不应从不受控切换到受控(反之亦然)。决定在组件的生命周期内使用受控输入元素还是不受控输入元素。

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

【问题讨论】:

  • 你应该使用 empty string 比如'' 而不是undefined
  • 另外,这不是问题的一部分,但想指出您的代码中有 useEffect 两次调用相同的函数。
  • 感谢@DragonWhite。

标签: javascript reactjs


【解决方案1】:

你应该使用像 '' 这样的空字符串而不是 undefined。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-14
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多