我的代码是这样的:
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时,所有属性值都更改为相同的值
答案 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>
);
}