1let markers = [ ...this.state.markers ];
2markers[index] = {...markers[index], key: value};
3this.setState({ markers });
1const initialState = [
2 { name: "foo", counter: 0 },
3 { name: "far", counter: 0 },
4 { name: "faz", counter: 0 }
5 ];
6
7const [state, setState] = useState(initialState);
8
9const clickButton = () => {
10 // 1. Make a shallow copy of the array
11 let temp_state = [...state];
12
13 // 2. Make a shallow copy of the element you want to mutate
14 let temp_element = { ...temp_state[0] };
15
16 // 3. Update the property you're interested in
17 temp_element.counter = temp_element.counter+1;
18
19 // 4. Put it back into our array. N.B. we *are* mutating the array here, but that's why we made a copy first
20 temp_state[0] = temp_element;
21
22 // 5. Set the state to our new copy
23 setState( temp_state );
24}
1this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
2this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
3
1let newMarkers = markers.map(el => (
2 el.name==='name'? {...el, key: value}: el
3))
4this.setState({ markers });