首页 > 解决方案 > 实现没有唯一 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: [],
};

标签: reactjscrud

解决方案


你可以传递一些信息来处理删除

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>


推荐阅读