0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactのfilter()でTodoを削除したら全部消えた話

Posted at

前提

恥ずかしながら勉強していてなぜか「?」と思ったので、まとめてみる。

あらかじめ記載しておきますが、初学者視点で自分の頭で理解できるようにまとめたものです。認識の違いや、理解の甘さ等、多々あると思いますが、あくまで自分のイメージの話です。しっくり来たのでまとめさせてもらいました。ご了承ください。

問題

Todoリストに削除ボタンが付いている。削除ボタンが押されたとき、todoを削除したい。
HTMLで以下のようなコードを書いた。
buttonタグが押された場合、DeleteTodo関数が動くというものだ。
しかし、buttonタグを押したとき、すべてのTodoリストが削除されてしまう

<ul>
    {TodoDates.map((todo) =>(
        <li key={todo.id}>
          <input type="text" value={todo.todo} onChange={(e) => ChangeTodo(e,todo.id)} disabled = {todo.check}/>
          <input type="checkbox" onChange={() => CheckTodo(todo.id,todo.check)} />
          <button onClick={(e) => DeleteTodo(e,todo.id) }>削除</button>
        </li>
        ))
        }
</ul>

以下が、DeleteTodo関数である。

  const DeleteTodo = ((e:React.MouseEvent<HTMLButtonElement>,id:number) => {
    console.log('削除ボタンが押されました')
    const NewTodo = TodoDates.filter((todo) => {
      todo.id !== id   //todo.idとidが揃わないやつだけ残すということ       
    })
    TodoDataFunction(NewTodo)        
  })

原因

以下の部分が原因だった。
filterのコールバック関数のブロック{}を使うと、returnを省略できないため、意図したフィルタリングが機能しなかった。

    const NewTodo = TodoDates.filter((todo) => {
      todo.id !== id   //これだけではリターンされない       
    })

解決策

returnを明示

    const NewTodo = TodoDates.filter((todo) => {
      return todo.id !== id   //todo.idとidが揃わないやつだけ残すということ       
    })

また、単純なfilter文であれば、returnを省略できる以下のような形でもよいだろう

const NewTodo = TodoDates.filter(todo => todo.id !== id)

まとめ

✅️filter() で {}(ブロック構文)を使う場合は return を明示する
✅️シンプルな条件なら () を使えば return を省略できる
✅️自分は基礎がまだまだのようだ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?