1

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

 [
        { 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

4

2 回答 2

4

尝试使用 Fat Arrow 方法来设置状态,如下所示:

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

如果由于不同的异步调用等原因同时调用了两次 setter 函数,它可以避免状态丢失。

于 2020-08-30T17:25:02.063 回答
1

避免循环更新状态。更新状态如:

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

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

setLocalErrs(errObj)

由于errObj具有所有更新的状态值。

于 2020-08-30T17:34:13.467 回答