开发者问题收集

无法清除状态并从 useState 表单获取错误响应

2022-10-28
64

我在 Typescript React 中为我的表单而苦恼。基本上,我创建了 2 个简单组件 ButtonInput ,并将它们添加到另一个组件 Form ,我在其中创建了一个完整的表单。

提交后,我应该得到这样的结果:

telephone: "323423234"
email: "[email protected]"
message: "weklfnwlkf"
name: "less"
surname: "mess"

但提交后,我得到了这样的奇怪响应:

"": "323423234"
email: "[email protected]"
message: "weklfnwlkf"
name: "less"
surname: "mess"
telephone: ""

这有点奇怪,因为我几天前做过类似的事情,现在我不知道该怎么做。 这是我的 Form 代码示例

const Form = () => {
  interface FormDataType {
    telephone: string;
    name: string;
    surname: string;
    email: string;
    message: string;
  }
  const formData: FormDataType = {
    telephone: '',
    name: '',
    surname: '',
    email: '',
    message: '',
  };
  const [responseBody, setResponseBody] = useState<FormDataType>(formData);

  const clearState = () => {
    setResponseBody({ ...formData });
  };

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    setResponseBody({ ...responseBody, [name]: value });
  };
  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    console.log(responseBody);
    clearState();
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
        {FormData.map((option) => (
          <Input
            key={option.name}
            label={option.label}
            type={option.type}
            className={option.className}
            name={option.name}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
              handleChange(e)
            }
          />
        ))}
        <div className='div'>
          <Button
            type='submit'
            title={'Simple test'}
            className={'btn-primary'}
          />
        </div>
      </form>
    </>
  );
};
export default Form;

当我在 handleSubmit 函数中调用 clearState() 时,它不会刷新网页输入中的状态。

2个回答

我希望这就是它所需要的,我做了一些改变,但你可以将它应用到你的项目中

export default function App() {
  interface FormDataType {
    telephone: string;
    name: string;
    surname: string;
    email: string;
    message: string;
  }
  const formData: FormDataType = {
    telephone: "",
    name: "",
    surname: "",
    email: "",
    message: ""
  };

  const [values, setValues] = useState<FormDataType | any>(formData);

  // reset
  const reset = (newFormState = formData) => {
    setValues(newFormState);
  };

  // handleInputChange
  const handleInputChange = ({ target }: any) => {
    setValues({ ...values, [target.name]: target.value });
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    console.log(values);
    reset();
  };

  const data = [
    {
      type: "text",
      name: "name"
    },
    {
      type: "text",
      name: "surname"
    },
    {
      type: "email",
      name: "email"
    },
    {
      type: "tel",
      name: "telephone"
    },
    {
      type: "text",
      name: "message"
    }
  ];

  return (
    <>
      <form onSubmit={handleSubmit}>
        {data.map((option) => (
          <input
            key={option.name}
            value={values[option.name]}
            type={option.type}
            name={option.name}
            placeholder={option.name}
            onChange={handleInputChange}
          />
        ))}
        <div className="div">
          <button type="submit">Simple test</button>
        </div>
      </form>
    </>
  );
}
Jackson Quintero
2022-10-28

您的重置不起作用,因为您的输入 不受控制

要正确重置它们,您应该通过向它们传递 value 属性来使它们受控。它看起来像这样:

<Input
  key={option.name}
  label={option.label}
  type={option.type}
  className={option.className}
  name={option.name}
  value={responseBody[option.name]} // Add this
  onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
    handleChange(e)
  }
/>

这会将 responseBody 表单数据与输入值连接起来。

至于奇怪的控制台记录值,似乎至少一个 option.name 值为空/未定义(看起来像电话对象)。验证 FormData 是否包含完整且正确的值。

Brian Thompson
2022-10-28