我从我的后端收到一个像这样的数组的验证响应
[
{ param: "secondName", msg: "second name is required" },
{ param: "password", msg: "password is required" }
]
我的反应组件中有这样的状态
const [errs, setErrs] = useState({
firstName: null,
secondName: null,
password: null,
email: null,
})
目标是在我的状态下仅更改我response.params在表单提交中提到的字段,其余部分保持原样null。这是我尝试过的:
const submitFoo = () => {
console.log(localErrs) //all props are set to null (default)
res.forEach((single) => {
setLocalErrs({
...localErrs,
[single.param]: single.msg
});
});
console.log(localErrs);//only password is set to the `response.msg`, instead of `password` AND `secondName`
};
但问题是它只改变了我的“错误状态”中的最后一项;输出是:
{
first: null,
second: null,
password: 'password is required',
email: null,
}
ps:我通过遍历数组并将Errs obj的道具直接设置为response.msg来尝试使用vanilla js并且它有效。所以问题必须与反应setstate