javascript - 如何更新对象数组中的 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,
};
解决方案
在回答之前,我必须提到!!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;
. 或者,您可能根本不需要返回。 - 我建议您将
state
和setState
变量名称更改为更有意义的名称,例如products
和setProducts
- 同样,我希望您的代码示例的中间部分属于一个函数,否则会弄乱您的组件(应该返回一个渲染函数)
推荐阅读
- reactjs - 如何将 Promise 转换为字符串?我使用了 Axios 并将数据返回到我的反应组件
- python - 如何在 matplotlib 中绘制常规网格作为背景
- maven - Bower:未定义复制原语
- xml - 在 Odoo 的报告/xml 中使用系统参数
- javascript - React - 重新渲染
- python - 如何从数据框创建集合
- powershell - Vagrant 访问被拒绝:Windows 更新后启动错误
- python - 根据列数重构熊猫数据框
- python - 如何增加 pyplots 等高线图的颜色范围
- javascript - 如何使用 Knockout 在父 div 之间动态移动子 div?