鉴于我们必须传递与 props 相同的对象,如何不可变地更新对象?

How to immutable update an object given that we have to pass the same object as props?

我有一个对象 amounts 会在单击按钮时更新。 Ans 我将该对象作为道具传递给另一个组件。我现在正在做的是在按钮单击事件上以可变方式更新对象。

onClick = e => {
  amounts.map(
      amount => (amount.tax = taxes ? 500 : 0)
  );
}

<Display amounts={amounts} />

如何以不可变的方式更新金额?

如评论中所述,发生了一些事情:

  1. 您没有更新 amounts 数组引用,因此 React 不会基于此更改重新呈现。
  2. 您正在使用 Array#map 更新单个 属性。 更新金额集合中的对象引用。
  3. 没有 setAmounts 或任何类似的东西来更新父组件中 amount 属性 的值。

假设您在 <Display /> 的父组件中使用 useState,您将必须使用 props 将 setAmounts 函数传递给 <Display /> 组件。

<Display amounts={amounts} setAmounts={setAmounts} />
onClick = e => {
  setAmounts(
    amounts.map(
      amount => ({ ...amount, tax: taxes ? 500 : 0 })
    );
  );
}