如何在向数组添加对象的同时将数组中其他对象的popup属性设为false?
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 useprevStateinstead ofthis.stateto get the most recent state value, which is crucial for avoiding race conditions in asynchronous state updates. - Map over existing areas: The
mapfunction creates a new array where every existing area object is copied, and itspopupproperty is set tofalse. 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

