In a React application, updating the state of an array or object can be tricky. This article will walk you through如何更新 state.item[1] in the state using setState, a common task in React.
Within the provided React component, the goal is to create a dynamic form where users can design their own fields. The state initially looks like this:
this.state.items[1] = { name: 'field 1', populate_at: 'web_start', same_as: 'customer_name', autocomplete_from: 'customer_name', title: '' };
The issue arises when trying to update the state when a user changes any of the values. Targeting the correct object becomes difficult.
To update the state correctly, follow these steps:
Example Implementation:
handleChange: function (e) { // 1. Make a shallow copy of the items let items = [...this.state.items]; // 2. Make a shallow copy of the item you want to mutate let item = {...items[1]}; // 3. Replace the property you're intested in item.name = 'newName'; // 4. Put it back into our array. N.B. we *are* mutating the array here, // but that's why we made a copy first items[1] = item; // 5. Set the state to our new copy this.setState({items}); }
Alternative Implementations:
let item = {...items[1], name: 'newName'}
this.setState(({items}) => ({ items: [ ...items.slice(0, 1), {...items[1], name: 'newName'}, ...items.slice(2) ] }));
The above is the detailed content of How to Update `state.item[1]` with `setState` in React?. For more information, please follow other related articles on the PHP Chinese website!