reactjs - 实现没有唯一 ID 的 Reactjs CRUD 应用程序
问题描述
我正在使用 Reactjs 创建一个 CRUD 应用程序,但我很难实现DELETE功能。我使用key={item + 1}
为数组中的每个存储项目生成一个唯一 ID,但我真的不知道如何评估它。这是我的代码......
列表
<ul>
{this.state.items.map(item => (
<li key={item + 1}>
{item}
<button>edit</button>
<button onClick={this.handleDelete}>delete</button>
</li>
))}
</ul>;
删除功能
handleDelete(id) {
let items = this.state.items;
this.setState({
items: this.state.items.filter(item => items.id !== id),
});
}
状态
this.state = {
input: '',
items: [],
};
解决方案
你可以传递一些信息来处理删除
handleDelete(id){
let items = this.state.items.filter(item => items.id !== id);
this.setState({
items: items
});
}
<ul>
{
this.state.items.map(item => (
<li key={item.id}>
{item}
<button>edit</button>
{/* here I send id of current item */}
<button onClick={()=>this.handleDelete(item.id)}>delete</button>
</li>
))}
</ul>
更新。忽略 id 你可以使用 key => index
handleDelete(key){
let items = this.state.items.filter((item, mapKey) => key !== mapKey);
this.setState({
items: items
});
}
<ul>
{
this.state.items.map((item, key) => (
<li key={key}>
{item}
<button>edit</button>
{/* here I send id of current item */}
<button onClick={()=>this.handleDelete(key)}>delete</button>
</li>
))}
</ul>
推荐阅读
- javascript - 映射两个数组以将不同的数据合并到一个 IF 项目 id 在 javascript 中是相同的
- ionic-framework - Ionic 3后台模式返回为假
- node.js - 如何使用节点 js 使用 mongobd 激活和停用用户帐户
- c# - 无法将两个参数传递给操作 ASP.NET MVC
- wordpress - 有人知道如何更改 WordPress 上的灰色 URL 吗?
- python - 如何使用 tkinter python 在控制台底部显示进度条
- sql - 如何在sql oracle中比较两个日期时间
- sql - 拆分日志以分隔行红移
- python - 如何在 html django 中过滤模型
- r - 如何在 R 中合并 101 个栅格文件?