在 React 中更新对象状态的特定字段

发布于 2025-01-19 02:53:12 字数 325 浏览 2 评论 0原文

我正在使用一个反应功能组件,在其中我只想更新状态的特定字段,并像以前一样保留其他值。这是状态初始化 -

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

红颜悴 2025-01-26 02:53:12

您正在做的是正确的。

这是根据状态的当前值更新状态的正确方法。它称为setState调用的功能形式。

setState((prevState) => {
  // Do something with prevState
  return newState; // Be aware to not mutate the prevState directly
});

示例:

// Array

setState((prevState) => {
  const newState = Array.from(prevState);
  newState.push('foo');
  return newState;
});

// Object

setState((prevState) => {
  return({
    ...prevState,
    foo: 'bar'
  });
});

主要的是对象/数组参考需要更改!

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.

setState((prevState) => {
  // Do something with prevState
  return newState; // Be aware to not mutate the prevState directly
});

Examples:

// Array

setState((prevState) => {
  const newState = Array.from(prevState);
  newState.push('foo');
  return newState;
});

// Object

setState((prevState) => {
  return({
    ...prevState,
    foo: 'bar'
  });
});

The main thing is that the object/array reference needs to change!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文