使用.map(Javascript/Rect)获取数组中要删除的元素的索引



我有一组成分要在我的React应用程序中显示为列表。与每个项目关联的是一个Delete按钮,单击该按钮时,将从数组中删除该特定元素,并使用更新后的数组重新渲染。

有没有办法找到元素的索引并将其传递给handleDelete()函数?

或者是循环遍历所有元素以查找和删除的唯一方法?

handleDelete(id) {
//use id to remove element from the array 
//setState of newly filtered array 
}

render() {
var ingredients = ["chicken", "rice"]
return (
<ul className="pantry"> 
{
ingredients.map((ingred, index) => {
return <li key={ingred.index}><button onClick={this.handleDelete.bind(this, ingred.index)}>Delete</button>{ ingred }</li>
})
} 
</ul>
);
}

你似乎已经完成了。您只需要在方法中创建一个闭包,然后实际返回回调函数。你还需要将原料储存在状态中。(我也清理了一些代码。(

constructor(props) {
super(props);
this.state = {
ingredients: ["chicken", "rice"],
};
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete(indexToDelete) {
//use id to remove element from the array 
//setState of newly filtered array
return (event) => {
this.setState((currentState) => {
const currentIngredients = currentState.ingredients;
return {
ingredients: currentIngredients.slice(0, indexToDelete - 1).concat(currentIngredients.slice(i, currentIngredients.length)),
};
});
}; 
}
renderIngredient(ingredient, index) {
return (
<li key={ingred}>
<button onClick={this.handleDelete(index)}>
Delete
</button>
{ingredient}
</li>
);
}
render() {
return (
<ul className="pantry"> 
{
this.state.ingredients.map(this.renderIngredient)
} 
</ul>
);
}

最新更新