如何使用索引来识别被点击的 Todo?

基本上我需要删除一个被点击的 ToDo,但是因为 ToDo 没有唯一的 id ..它删除了所有这些 .. 我尝试了 UUIDV4 但我没有成功地将它添加到每个 ToDo


应用程序.js


class App extends Component {

  state = {

    input: "",

    todo: [],

    completed: false

  };


  handleRemove = (id) => {

    const remove = this.state.todo.filter((todo) => 

    todo.key !== id.key);

    this.setState({todo: remove});

  }


...

 <TodoList 

          todo={this.state.todo}

          rmv={this.handleRemove}

        />

待办事项列表


const TodoList = ({todo, rmv}) => {

    const todoBuild = todo.map((todo, index) => (

      <Todo 

        todo={todo} 

        key={index} 

        rmv={rmv}/>

    ))

    return <div> {todoBuild} </div>

};

去做


const Todo = ({todo, rmv}) => {

    return (

        <div className='todo'>

            <p>{todo}</p>

            <button className='btn-rmv' onClick={() => rmv (todo)}>x</button>

        </div>

    )

}


饮歌长啸
浏览 139回答 1
1回答

缥缈止盈

数组是有序结构,因此您可以依赖项目索引,即使在序列化/反序列化之后也将保持不变。注意(感谢@devserkan):...本示例中使用的扩展运算符 ( ) 创建数组的浅拷贝,以防万一您使用嵌套数组 - 请splice修改原始数组(这是您永远不想做的)。请使用方法创建数组的深层副本(JSON.parse(JSON.stringify(...)),lodash 库方法等)或splice用Array.filter.移除功能handleRemove = (id) => {&nbsp; &nbsp; let todo = [...this.state.todo]&nbsp; &nbsp; todo.splice(id, 1);&nbsp; &nbsp; this.setState({todo});&nbsp; }待办事项列表const TodoList = ({todo, rmv}) => {&nbsp; &nbsp; const todoBuild = todo.map((todo, index) => (&nbsp; &nbsp; &nbsp; <Todo&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; itemIndex={index}&nbsp; &nbsp; &nbsp; &nbsp; todo={todo}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; key={index}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; rmv={rmv}/>&nbsp; &nbsp; ))&nbsp; &nbsp; return <div> {todoBuild} </div>};去做const Todo = ({todo, rmv, itemIndex}) => {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div className='todo'>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>{todo}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button className='btn-rmv' onClick={() => rmv(itemIndex)}>x</button>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript