You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在向数组添加对象的同时将数组中其他对象的popup属性设为false?

Solution for Updating Array with Popup State

Got it, let's fix this so that when you add a new object to your areas array, all existing objects have their popup property set to false, while the new one stays true.

The key here is to first modify all existing items in the array before adding the new entry, and use functional setState to ensure we're working with the latest state (since setState is asynchronous, relying directly on this.state can lead to stale data).

Here's the adjusted code:

this.setState(prevState => ({
  map: {
    ...prevState.map,
    areas: [
      // Update all existing areas to have popup: false
      ...prevState.map.areas.map(area => ({
        ...area, // Copy all existing properties of the area
        popup: false // Override the popup property
      })),
      // Add the new area with popup: true
      {
        coords: [evt.nativeEvent.layerX, evt.nativeEvent.layerY, 15],
        popup: true
      }
    ]
  }
}));

Breakdown of what's happening:

  • Functional setState: We use prevState instead of this.state to get the most recent state value, which is crucial for avoiding race conditions in asynchronous state updates.
  • Map over existing areas: The map function creates a new array where every existing area object is copied, and its popup property is set to false. We don't mutate the original objects—we create new ones to follow React's immutability rules.
  • Add the new area: We append the new object (with popup: true) to the end of the updated array using the spread operator (...).

Alternatively, if you prefer using concat instead of the spread operator, this works too:

this.setState(prevState => {
  // First update all existing areas
  const updatedExistingAreas = prevState.map.areas.map(area => ({
    ...area,
    popup: false
  }));
  // Add the new area to the updated array
  const newAreas = updatedExistingAreas.concat({
    coords: [evt.nativeEvent.layerX, evt.nativeEvent.layerY, 15],
    popup: true
  });

  return {
    map: {
      ...prevState.map,
      areas: newAreas
    }
  };
});

Either approach will ensure that only the newly added object has popup: true, and all others are set to false when the state updates.

内容的提问来源于stack exchange,提问作者SecondClassCitizen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:22:35