首页 > 解决方案 > 如何更新对象数组中的 React 状态?如果 id 存在则更新,否则追加

问题描述

父组件通过回调函数从子组件获取对象。我想检查具有特定 rowID 的对象是否存在,如果存在,则应使用传递的值“val”更新对象,否则应将对象附加到状态数组中。我的答案正确附加,但我无法更新值,请帮帮我。正在传递的对象最后附加。

const [state, setState] = React.useState([]);

const existingProduct = state && state.find((product) => product.rowID == index);
if (!!existingProduct === false) {
  return setState((prevState) => [...prevState, object]);
}
console.log(state);

let payload = {
          quantity: quantityRef.current && 
          quantityRef.current.value,
          name: product && product.NAME,
          unit: product && product.UNIT,
          PRICE: product && product.PRICE,
          oldQuantity: oldQuantity,
          rowID: id,
        };

标签: javascriptreactjsstate

解决方案


在回答之前,我必须提到!!existingProduct === false阅读起来非常混乱。你可以简单地做!existingProduct来达到同样的结果。

您的代码缺少某些部分,因此我将不得不推断,但我假设该index值符合您的要求,并且您已经在检测该产品是否存在于数组中。而且您将新产品附加到 中if,所以我们需要的是else.

我要做的是将状态复制到一个新数组中,替换新数组中的值,并将这个新数组设置为新状态。要知道需要更新数组的哪个位置,可以使用findIndex()方法而不是find(). 因此,它不是existingProduct一个对象,而是包含该对象的数组的索引(所以我会称它为existingProductIdx清楚起见):

if (existingProductIdx === -1) { // product doesn't exist in the array
  ...
} else { // product exists
  const newSate = [...state] // creates a copy of the current array
  newState[existingProductIdx] = payload // set the position of the array to payload (or whatever should be the new value)
  return setState(newState)
}

几点注意事项:

  • 我假设你在一个你想早点返回的函数中执行此操作,这就是你有该return语句的原因。否则你不需要它
  • 我现在不记得了,但我很确定setState没有返回值,所以你可以做setState(newState); return;. 或者,您可能根本不需要返回。
  • 我建议您将statesetState变量名称更改为更有意义的名称,例如productssetProducts
  • 同样,我希望您的代码示例的中间部分属于一个函数,否则会弄乱您的组件(应该返回一个渲染函数)

推荐阅读