Map over State or prevState in setState?

huangapple go评论66阅读模式
英文:

Map over State or prevState in setState?

问题

这是您要翻译的部分:

使用state直接:

// 重置选择
setAmountData(
  amountData.map(amount => {
    return {
      ...amount,
      selected: false,
    };
  }),
);

使用prevState

// 重置选择
setAmountData(prevState =>
  prevState.map(amount => {
    return {
      ...amount,
      selected: false,
    };
  }),
);
英文:

I have an array of objects which I want to loop through and reset the selected value for each item to false:

// Amount data state
const [amountData, setAmountData] = useState([
  {
    id: 30,
    amount: (30000).toLocaleString(),
    selected: true,
  },
  {
    id: 10,
    amount: (10000).toLocaleString(),
    selected: true,
  },
  {
    id: 70,
    amount: (70000).toLocaleString(),
    selected: true,
  },
  {
    id: 50,
    amount: (50000).toLocaleString(),
    selected: true,
  },
]);

What I was wondering is if the correct way of updating the state in setState is to loop through the current state directly (amountData) or loop through the prevState and if either way would have any benefit over the other method?

Using state directly:

// Reset selection
setAmountData(
  amountData.map(amount => {
    return {
      ...amount,
      selected: false,
    };
  }),
);

Using prevState:

// Reset selection
setAmountData(prevState =>
  prevState.map(amount => {
    return {
      ...amount,
      selected: false,
    };
  }),
);

答案1

得分: 1

使用prevState来基于React中的先前状态更新状态是推荐的。因为React状态更新可能是异步的,如果您直接依赖于当前状态,您可能会得到陈旧或不正确的状态值。

使用prevState可以确保在进行更新时始终使用最新的状态值。
因此,您应该使用prevState,这更安全,并确保在更新amountData状态时使用正确的状态值。

英文:

It's recommended to use the prevState when updating state based on the previous state in React. Because React state updates may be asynchronous, and if you rely on the current state directly, you might end up with stale or incorrect state values.

Using prevState ensures that you're always working with the most up-to-date state values when making updates.
So you should use prevState which is safer and guarantees that you're working with the correct state values when updating the amountData state.

// Reset selection
setAmountData(prevState =>
  prevState.map(amount => {
    return {
      ...amount,
      selected: false,
    };
  }),
);

答案2

得分: 1

如在React文档中提到的,如果你只是将下一个状态值传递给setState,而且在处理程序中有多个这样的setState,它们都会被批处理,只有一个会应用到状态值上。

然而,传递一个函数,该函数接受prevState,并根据该值对状态变量进行更改,不会引起这种批处理。

在你的情况下,因为你只调用一次setState,两种方法都会产生相同的结果。

我已经创建了一个sandbox,你可以在其中尝试我的代码,并查看控制台以更好地理解这一点。

英文:

As mentioned in the React docs , if you just pass on the next state's value to a setState, and have multiple such setStates in your handler, all of them get batched, and only one gets applied to your state value.

However, passing a function that takes the prevState, and applies changes to the state variable based on whatever that value is, does not cause this batching.

In your case, since you only have setState once, both the methods yield the same result.

I have gone ahead and created a sandbox where you can experiment with my code and look at the console to better understand this.

答案3

得分: 0

setState(prevState => ...) 这种写法只在连续多次使用 setState 时才需要。并没有强制建议总是使用这种写法,它取决于个人偏好。参见 https://react.dev/reference/react/useState#is-using-an-updater-always-preferred

你可能会听到建议,如果要设置的状态是基于先前状态计算的,应始终编写类似 setAge(a => a + 1) 的代码。这样做没有问题,但也不总是必要。
[...]
如果你更看重一致性而不介意多写一些代码,那么始终编写一个更新函数是合理的,如果要设置的状态是基于先前状态计算的。

英文:

You really only need to use the setState(prevState => ...) synthax if you have multiple setState calls in a row.

There is no recommendation to always use this synthax, it's a matter of preference. See https://react.dev/reference/react/useState#is-using-an-updater-always-preferred

> You might hear a recommendation to always write code like setAge(a => a + 1) if the state you’re setting is calculated from the previous state. There is no harm in it, but it is also not always necessary.
[...]
If you prefer consistency over slightly more verbose syntax, it’s reasonable to always write an updater if the state you’re setting is calculated from the previous state.

huangapple
  • 本文由 发表于 2023年4月11日 13:56:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定