简体   繁体   English

更新对象的 useState 数组中的 object 值

[英]Update object value in useState array of objects

I am currently struggling with changing a couple of states that I currently have in my web app.我目前正在努力改变我目前在我的 web 应用程序中拥有的几个状态。 The state is as follows: state如下:

const [points, setPoint] = useState([]);

Which stores the data like this:它存储这样的数据:

0: (2) [{…}, {…}]
1: (2) [{…}, {…}]

In other words, the array contains each an array of two objects.换句话说,该数组中的每一个都包含一个由两个对象组成的数组。 The content looks like this;内容是这样的;

0:
elementId: 0
elementPosX: 615
elementPosY: 171
1:
elementId: "liiMJzWgphZPbnx"
elementPosX: 618.5
elementPosY: 317

I want to search if x is equal to the elementId , and then change the values directly linked to this object.我想搜索x是否等于elementId ,然后更改直接链接到此 object 的值。 How can I achieve this?我怎样才能做到这一点?

I have found a way to edit an object in a regular single array of objects like so:我找到了一种在常规单个对象数组中编辑 object 的方法,如下所示:

setPoint(singlePoint.map(x => {
  if (x.id !== id) return x
  return { ...x, position: { x: xPosition - 365, y: yPosition - 80 } }
}))

This works, but I'm not sure if there is an easier way of doing this?这行得通,但我不确定是否有更简单的方法可以做到这一点?

If you care about the array order.如果您关心数组顺序。 You have first to find the element index and then update it:您必须首先找到元素索引,然后对其进行更新:

setPoint((allPoints) => {
  const index = allPoint.findIndex((element) => element.id === x.id);
  allPoints[index] = {
    ...x,
    position: { x: xPosition - 365, y: yPosition - 80 },
  };
  return allPoints;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM