Important point is, we should not mutate the state array directly, always do the changes in new array and then use setState to update the state value.
As suggested by Doc:
Never mutate this.state directly, Treat this.state as if it were
immutable.
Basic flow of updating a state array is:
1- First create the copy of state array.
2- Find index of the item (if index is available skip this one).
3- Update the value of item at that index.
4- Use setState to update the state value.
Multiple solutions are possible:
1- Use array.map and check which element you want to update, when you find that element return a new object for that with updated key value otherwise just return the same object. Like this:
let newMarkers = markers.map(el => (
el.name==='name'? {...el, key: value}: el
))
this.setState({ markers });
2- We can also use array.findIndex to find the index of that particular item, then update the values of that item. Like this:
let markers = [...this.state.markers];
let index = markers.findIndex(el => el.name === 'name');
markers[index] = {...markers[index], key: value};
this.setState({ markers });
Loop will be not required if we know the index of the item, directly we can write:
let markers = [ ...this.state.markers ];
markers[index] = {...markers[index], key: value};
this.setState({ markers });
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…