Home >Web Front-end >JS Tutorial >How to Safely Remove Items from an Array in React State?
Modifying Item Lists in React: Removing Elements
In React, managing state is crucial for manipulating app data. Consider a scenario where you have an array called "people" in your state, and you need to remove an item (e.g., "Bob") from it. However, simply deleting the item directly might not produce the desired result.
In this instance, it's essential to avoid directly mutating state objects (including arrays). To efficiently modify the "people" array, create a new copy of it with the desired changes.
One approach is to use the Array.prototype.filter() method:
removePeople(e) { this.setState({ people: this.state.people.filter(function (person) { return person !== e.target.value; // Exclude the target person ("Bob") }) }); }
This method creates a new array containing all elements that do not match the provided condition (i.e., "Bob"). The original "people" array remains intact, and the new array is assigned to the state, ensuring that your application reacts to the updated state properly.
The above is the detailed content of How to Safely Remove Items from an Array in React State?. For more information, please follow other related articles on the PHP Chinese website!