[英]Modify an array of objects using useState()
I have an array of objects and when my component mounts I want to modify a property on the objects in the array.我有一个对象数组,当我的组件挂载时,我想修改数组中对象的属性。
For context: I am loading a component, waiting for the images to load, then i get the image dimensions and then i figure out the aspect ratio and change that value in the array.对于上下文:我正在加载一个组件,等待图像加载,然后我得到图像尺寸,然后我计算出纵横比并更改数组中的值。
Here is some reduced code for readability:以下是一些简化的代码以提高可读性:
let itemsOriginal = [
{
id: 1,
src: "<img-src>",
aspectRatio: null
},
{
id: 2,
src: "<img-src>",
aspectRatio: null
},
{
id: 3,
src: "<img-src>",
aspectRatio: null
}
];
const [items, setArr] = useState(itemsOriginal);
useEffect(() => {
// figure out aspect ratio
// then try and set that value to obj property in array
setArr(
items.map((item, index) => {
item.aspectRatio === null
? {...item, aspectRatio: "changed"} // <<< how do i get item.aspectRatio to update ???
: ''
}
))
})
You can do,你可以做,
const update = () => {
const itemsClone = [...items];
itemsClone.forEach((p) => {
p.aspectRatio = 'new value';
});
setArr(itemsClone);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.