CODE:
handleDeleteClick: function(index) {
var newRecipesArray = this.state.recipesArray;
newRecipesArray.splice(index-1,1);
this.setState({
recipesArray: newRecipesArray
});
},
render: function() {
var i = 0;
var that = this;
var recipes = this.state.recipesArray.map(function(item) {
i++
return (
<div key={"div"+i} className="table">
<Recipe key={i} name={item.name} ingredients={item.ingredients} />
<button key ={"edit"+i} onClick={() => { that.handleEditClick(i)}} className="btn edit btn-primary">Edit</button>
<button key ={"delete"+i} onClick={() => { that.handleDeleteClick(i)}} className="btn delete btn-danger">Delete</button>
</div>
);
});
return (
<div>
<h1>React.js Recipe Box</h1>
<button className="btn btn-primary" onClick={this.handleClick}>Add Recipe</button>
<table>
<tbody>
<tr>
<th>RECIPES</th>
</tr>
</tbody>
</table>
{recipes}
{ this.state.adding ? <AddRecipe handleClose={this.handleClose} handleAdd={this.handleAdd} /> : null }
{ this.state.editing ? <EditRecipe currentIndex = {this.state.currentIndex} handleClose={this.handleClose} handleEdit={this.handleEdit}/> : null }
</div>
);
},
});
状况:
当我点击删除时,它始终是删除的最后一个元素,而不是应该链接到该特定删除按钮的元素。
错误在哪里,我该如何解决?
答案 0 :(得分:1)
Map将index作为第二个参数,因此不需要单独的索引变量。此外,您不需要所有元素的键,只需要父元素
handleDeleteClick: function(index) {
var newRecipesArray = this.state.recipesArray;
newRecipesArray.splice(index,1);
this.setState({
recipesArray: newRecipesArray
});
},
render: function() {
var that = this;
var recipes = this.state.recipesArray.map(function(item, i) {
return (
<div key={"div"+i} className="table">
<Recipe name={item.name} ingredients={item.ingredients} />
<button onClick={() => { that.handleEditClick(i)}} className="btn edit btn-primary">Edit</button>
<button onClick={() => { that.handleDeleteClick(i)}} className="btn delete btn-danger">Delete</button>
</div>
);
});