从React的待办事项列表中删除一个待办事项。

huangapple go评论60阅读模式
英文:

Removing a todo from todo list in react

问题

I am creating this todo list app, but I can't seem to find out how to make the react icon when clicked to delete that value that it's next to.

我正在创建这个待办事项列表应用,但似乎无法弄清楚如何使点击时的 React 图标删除其旁边的值。

I tried doing this:

我尝试了以下方法:

const click = () => {
setTodos(todos => todos.filter((item) => item.id));
}

return (
<>

Your Todos

<NewTodo onAdd={(newTodo) => setTodos([...todos, newTodo])} />

    {visibleTodos.map((todo) => (

  • {todo.text}
  • ))}

</>
);

When I clicked the icon next to the todo it got deleted, but when I tried deleting another value it didn't work. I could only delete one todo.

当我点击待办事项旁边的图标时,它会被删除,但当我尝试删除另一个值时,它不起作用。我只能删除一个待办事项。

英文:

I am creating this todo list app, but I can't seem to find out how to make the react icon when clicked to delete that value that it's next to.

I tried doing this:

const click = () =&gt; {
    setTodos(todos =&gt; todos.filter((item) =&gt; item.id));
  }

  return (
    &lt;&gt;
    &lt;h2&gt;Your Todos&lt;/h2&gt;
     &lt;NewTodo onAdd={(newTodo) =&gt; setTodos([...todos, newTodo])} /&gt;
      &lt;ul&gt;
    {visibleTodos.map((todo) =&gt; (
      &lt;li key={todo.id}&gt;
        {todo.text}
        &lt;button onClick={click}&gt;&lt;AiFillDelete /&gt;&lt;/button&gt;
          &lt;/li&gt;    
        ))}
      &lt;/ul&gt;
     &lt;/&gt;
    );
   }

When I clicked the icon next to the todo it got deleted, but when I tried deleting another value it didn't work. I could only delete one todo.

答案1

得分: 0

This is meant to filter:

todos.filter((item) => item.id)

This code returns all items that have an ID, which is probably all of them.

Typically, you would filter items based on a condition. For example, to filter items that don't match a specific ID:

todos.filter((item) => item.id !== id)

In this case, you need a value for id, which can be passed to the function:

const click = (id) => {

Then, you can pass the ID to the function like this:

onClick={() => click(todo.id)}
英文:

What is this meant to filter?:

todos.filter((item) =&gt; item.id)

This is returning all items which have an ID, which is probably all of them, no? Generally you would filter items which match a condition. For example, all items which don't match a specific ID:

todos.filter((item) =&gt; item.id !== id)

So then you'd need a value for id, which can be passed to the function:

const click = (id) =&gt; {

And then you'd just need to pass the ID to the function:

onClick={() =&gt; click(todo.id)}

huangapple
  • 本文由 发表于 2023年4月19日 18:52:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76053652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定