使用 useState 和 prev 状态更新状态时出现问题



我的代码是这样的:

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;
}
};

但是当我只更改电子邮件和控制台.log((注册表表单状态时,所有属性值都以相同的值更改

您可以使用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>
);
}

相关内容

  • 没有找到相关文章

最新更新