![](/img/trans.png)
[英]How to delete objects inside an object using an array? (React.js Reducer )
[英]React.js - How to change object value inside array of objects
我对 state 内的对象数组有疑问。 我的问题是如何更改 object 值,如下面的示例代码
const [theArrayOfObjects, setTheArrayOfObjects] = useState([
{ color: "blue", shape: "square" },
{ color: "red", shape: "circle" }
]);
我想要的是
[
{ color: "blue", shape: "square" },
{ color: "red", shape: "rectangle" }
]
所以简而言之,我只想通过仅更改此特定值来更新对象数组
setTheArrayOfObjects([
{ color: "blue", shape: "square" },
{ color: "red", shape: "rectangle" }
]
)
虽然这可能不完全符合您的要求,但它符合您的需求并且很简单。 进一步的复杂性,例如遍历每个元素并找到到达特定元素的模式可能最终会出现意外的输出。
如果你不喜欢这个,那么你可能会想出不同的 state 结构(一个 object 而不是一个数组)。
使用功能性 state 更新从任何先前的 state 值正确更新。 浅拷贝您正在更新的 state 的任何部分。 请记住, useState
state 更新程序 function 不会浅合并您的更新,您将返回一个全新的 state 值。
鉴于:
const [theArrayOfObjects, setTheArrayOfObjects] = useState([
{ color: "blue", shape: "square" },
{ color: "red", shape: "circle" }
]);
更新如下:
例子:
const updateShape = (shape, index) => {
setTheArrayOfObjects(state => state.map((el, i) => i === index
? { ...el, shape }
: el,
));
};
...
updateShape("rectangle", 1);
尽管它来自 Redux,但不可变更新模式文档对于更详细地解释我上面描述的内容非常有帮助,并且仍然适用于标准 React state 更新。 请读一读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.