I am new to React.js and I want to delete the current div
that is generated in a map
function. When I click on delete button it deletes the last element of the array array instead of the clicked element.
Here is my code:
{
this.state.array.map((item,index)=>{
return(
<div key={index}>
<Question />
<button onClick={() => { this.deleteRow(index); }}>DELETE</button>
</div>
);
})
}
and this is my delete function
deleteRow = (index) => {
// make new rows. note: react state is immutable.
let newArray = this.state.array;
newArray.pop(newArray[index]);
this.setState({
array: newArray,
});
console.log(this.state.array);
}
<button onClick={() => this.deleteRow(item)}>DELETE</button>
change this code
deleteRow = (item) => {
let newArray = this.state.array;
let filtered = newArray.filter(a=>a.id!==item.id);
this.setState({array: filtered});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.