在 React 中更新对象状态的特定字段
我正在使用一个反应功能组件,在其中我只想更新状态的特定字段,并像以前一样保留其他值。这是状态初始化 -
const[value, setValue] = React.useState({
a: "5",
b: "6"
});
我只想将“ a”的值更新为其他东西,假设7(同时保留“ b”的值相同的值)。我目前正在这样做 -
setValue(currValue => ({
...currValue,
a: "7"
}))
这是错误的吗?如果是的,那么正确的方法是什么?
I am using a React functional component where I want to update only a specific field of the state and retain the other values like before. Here's the state initialization -
const[value, setValue] = React.useState({
a: "5",
b: "6"
});
I wish to only update value of 'a' to something else, let's say 7 (whilst retaining the same value for 'b'). Currently I am doing this -
setValue(currValue => ({
...currValue,
a: "7"
}))
Is this wrong ? If yes, what's the correct way of doing it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在做的是正确的。
这是根据状态的当前值更新状态的正确方法。它称为
setState
调用的功能形式。示例:
主要的是对象/数组参考需要更改!
What you are doing is correct.
That's the proper way for updating the state based on the current value of the state. It's called the functional form of the
setState
call.Examples:
The main thing is that the object/array reference needs to change!