react setstate 在循环中不能正常工作

react setstate does not work properly on loops

我从我的后端收到一个像这样的数组形式的验证响应

 [
        { param: "secondName", msg: "second name is required" },
        { param: "password", msg: "password is required" }
 ]

我的 React 组件中有这样一个状态

  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 的 props 直接设置为 response.msg 来尝试使用 vanilla js,它成功了。所以问题必须与 react setstate

尝试使用 Fat Arrow 方法设置状态如下:

setLocalErrs(localErrs => ({ ...localErrs, [single.param]: single.msg }));

它避免了在 setter 函数由于不同的异步调用等原因同时被调用两次的情况下的状态丢失

避免更新 state in a loop。更新状态如:

let errObj = {}
res.forEach((single) => {
  errObj[single.param] = single.msg
})
setLocalErrs({
  ...localErrs,
  ...errObj
})

顺便说一句,您可以简单地使用:

setLocalErrs(errObj)

因为 errObj 具有所有更新的状态值。