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}
1const handleAdd = (todo) => {
2 const newTodos = [...todos];
3 newTodos.push(todo);
4 setTodos(newTodos);
5}
6
1this.setState(({items}) => ({
2 items: [
3 ...items.slice(0,1),
4 {
5 ...items[1],
6 name: 'newName',
7 },
8 ...items.slice(2)
9 ]
10}));
11
1let newMarkers = markers.map(el => (
2 el.name==='name'? {...el, key: value}: el
3))
4this.setState({ markers });