用useState和prev状态更新状态的问题

时间:2020-05-11 10:23:51

标签: javascript reactjs forms web-applications react-hooks

我的代码是这样的:

const [registryFormState, setRegistryFormState] = useState({
    email: null,
    username: null,
    password: null,
    confirmPassword: null,
  });

  const changeFormHandler = (value, inputIdentify) => {
    switch (inputIdentify) {
      case 'email':
        return setRegistryFormState((prevState) => ({
          ...prevState,
          email: value,
        }));
      case 'username':
        return setRegistryFormState((prevState) => ({
          ...prevState,
          username: value,
        }));
      case 'password':
        return setRegistryFormState((prevState) => ({
          ...prevState,
          password: value,
        }));
      case 'confirmPassword':
        return setRegistryFormState((prevState) => ({
          ...prevState,
          confirmPassword: value,
        }));
      default:
        return;
    }
  };

但是当我只更改email和console.log()的RegistryFormState时,所有属性值都更改为相同的值

1 个答案:

答案 0 :(得分:-1)

您可以像这样使用registryFormState而不是prevState来进行解构:

import React from "react";

export default function Lol() {
  const [registryFormState, setRegistryFormState] = React.useState({
    email: null,
    username: null,
    password: null,
    confirmPassword: null
  });

  const changeFormHandler = (value, inputIdentify) => {
    switch (inputIdentify) {
      case "email":
        setRegistryFormState({
          ...registryFormState,
          email: value
        });
        break;
      case "username":
        setRegistryFormState({
          ...registryFormState,
          username: value
        });
        break;
      case "password":
        setRegistryFormState({
          ...registryFormState,
          password: value
        });
        break;
      case "confirmPassword":
        setRegistryFormState({
          ...registryFormState,
          confirmPassword: value
        });
        break;
      default:
        break;
    }
  };

  return (
    <div>
      <input onChange={e => changeFormHandler(e.target.value, "email")} />
      <input onChange={e => changeFormHandler(e.target.value, "username")} />
      <input onChange={e => changeFormHandler(e.target.value, "password")} />
      <input
        onChange={e => changeFormHandler(e.target.value, "confirmPassword")}
      />
      <button onClick={() => console.log(registryFormState)}>Submit</button>
    </div>
  );
}