React类组件中删除数组元素并保持有序列表序号连续的removeItem方法实现
Hey there! I see you're trying to get item removal working in your ProfileSettings component while keeping the list numbers continuous. Let's sort this out together.
Step 1: Correctly Implement the removeItem Method
First, we need to update the removeItem method to properly update the state without mutating the original array (a key React best practice). We'll create a new array that excludes the item at the passed index, then update the state with this new array.
Here's the implementation:
removeItem = (index) => { // Create a new array excluding the item at the specified index const updatedList = this.state.list.filter((_, idx) => idx !== index); // Update the state with the new array this.setState({ list: updatedList }); }
Step 2: Verify the Index is Passed Correctly
Looking at your render method, you're already correctly passing the index to removeItem here:
<IconButton className={(row.selected) ? "selectedDeleteIconclass" : "deleteIconclass" } style={{ float: "right" , marginLeft : 115,marginTop:-8}} onClick={() => this.removeItem(index)}> <Delete /> </IconButton>
That's perfect—this ensures we know exactly which item to remove.
Step 3: Why This Works for Continuous Numbering
Your render logic uses index + 1 for the list number:
<span style={{ marginTop: 2,color:(row.selected) ? "#FFF" : "black" }}>{index + 1}.</span>
Since index comes directly from the map function, when you remove an item, the map will iterate over the new, shorter array, and each remaining item's index will shift to fill the gap. This means the numbers will automatically stay continuous—no extra work needed!
Bonus: Fix the addListItem Method (Best Practice)
Your current addListItem mutates the original state array, which can lead to unexpected behavior. Let's update it to follow React's immutability rules too:
addListItem = () => { // Create a new array by spreading the existing list and adding the new item const updatedList = [...this.state.list, { text: "", selected: false }]; this.setState({ list: updatedList }); }
Full Updated Component Snippet
Here's how your component will look with these changes (I also added a sample implementation for changeRowSelectedOption since it's referenced but missing):
const ProfileSettings = observer( class ProfileSettings extends React.Component { constructor(props) { super(props) this.state = { expandIconPosition: 'left', buttonDisable: false, fetchedNotificationData: [], spinning: true, checkedA: true, checkedB: true, checkedC: true, list: [], }; } addListItem = () => { const updatedList = [...this.state.list, { text: "", selected: false }]; this.setState({ list: updatedList }); } removeItem = (index) => { const updatedList = this.state.list.filter((_, idx) => idx !== index); this.setState({ list: updatedList }); } // Sample implementation for row selection toggle changeRowSelectedOption = (row) => { const updatedList = this.state.list.map(item => item === row ? { ...item, selected: !item.selected } : item ); this.setState({ list: updatedList }); } render() { return ( <div style={{ backgroundColor: "#ffffff", borderRadius: 16, padding: 10, minHeight: 140, width: 406, borderRadius: 8, marginTop: 10, boxShadow: "0px 1px 3px 0px rgba(0, 0, 0, 0.2), 0px 2px 1px -1px rgba(0, 0, 0, 0.12), 0 1px 0 rgba(0, 0, 0, 0.14)" }}> {(this.state.list.length !== 0) ? this.state.list.map((row, index) => ( <div className="row" style={{borderRadius:4,marginLeft:5,marginRight:5,paddingLeft : 15, backgroundColor : (row.selected) ? "#1A32FF" : "#FFF" }}> <span style={{ marginTop: 2,color:(row.selected) ? "#FFF" : "black" }}>{index + 1}.</span> <TextField InputProps={{ style:{ color: row.selected ? 'white' : 'black' }, onClick:()=>this.changeRowSelectedOption(row) }}id="standard-basic" style={{ width: "50%",marginLeft:3 }}></TextField> <IconButton className={(row.selected) ? "selectedDeleteIconclass" : "deleteIconclass" } style={{ float: "right" , marginLeft : 115,marginTop:-8}} onClick={() => this.removeItem(index)}> <Delete /> </IconButton> </div> )) : null} </div> ) } })
Key Takeaways
- Always update React state immutably (don't modify the original array/object directly)
- Using the
mapindex for list numbering ensures continuity when items are removed, since the index automatically adjusts to the new array length - Passing the
mapindex to your removal method lets you target exactly the item to delete
内容的提问来源于stack exchange,提问作者Furkan Çetin

