javascript - How to delete a specific element from an component array?
问题描述
When my code executes to remove an element, the last array element gets deleted, not the specific index I am referring to in the code.
Any assistance in reviewing this would be helpful.
constructor(props) {
super(props);
this.state = {
rows: []
}
this.addHandler = this.addHandler.bind(this);
this.removeHandler = this.removeHandler.bind(this);
}
addHandler(event){
const rows = this.state.rows.concat(<Component>);
this.setState({
rows
})
}
removeHandler(id){
const index = id;
this.setState({
row: this.state.row.filter( (x, i) => i !== index)
})
}
render () {
const rows = this.state.rows.map((Element, index) => {
return <Element key={index} id={index} index={index} func1=
{this.addHandler} func2={this.removeHandler} />
});
// func2 gets called by child
return (
<div className="rows">
<button onClick={this.addHandler} >+</button>
{rows}
</div>
);
}
解决方案
Don't use index as a key for mapping out an array. Check out this package, easy to use and get the job done uuid