3
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初心者向け:useStateで配列にデータを追加する方法とつまずきポイントまとめ

3
Posted at

はじめに

ReactでuseStateを使って学習記録を再レンダリングする実装を行なったのですがうまく動かずハマりました。
今回はそのつまずきポイントと理解したことをまとめます。

問題

今回、つまずいたポイントは以下です。

  • handleClick実行時に、
    recordのオブジェクトの中身を何を定義すればいいのかわからなかった
  • JavaScriptの組み込みオブジェクトを知らなかった
  • setRecordsの表示のされ方がわからなかった

順に、解説していきます。

理解した点

1. handleClickでのオブジェクトの定義

 const handleClick = () => {
    const newStudy = {
      id: Date.now(),
      title: content,
      time: Number(time),
    };

ここでid,title,timeになるのは元の配列がこの形式のオブジェクトだからです。

const records = [
    { title: "勉強の記録1", time: 1},
    { title: "勉強の記録2", time: 3},
    { title: "勉強の記録3", time: 5}
]
  • idはReactでリストをレンダリングする際のkeyとして一意にするために使います。

2. JavaScriptの組み込みオブジェクト

  • Date.now():今の時間をミリ秒で数字として取得する。
    • 主な用途:ID生成、時間計測、時間の比較
  • time: Number(time)
    • 型をstringからNumberに変換させている。
    • なぜ必要か?:入力値はstring型なので、計算できるように数値型に変換する必要があります。

3.setRecordsの挙動

const [records, setRecords] = useState([]);

  const handleClick = () => {
    const newStudy = {
      id: Date.now(),
      title: content,
      time: Number(time),
    };

    setRecords([...records, newStudy]);
  • 初期値は空配列
  • handleClickでオブジェクトを作成
  • スプレッド構文、...recordsで既存配列を展開し、newStudyを追加
  • これにより状態が更新され、画面が再レンダリングされます。

スクリーンショット 2026-02-01 0.08.34.png

おわりに

今回の実装を通してuseStateでの配列更新の挙動が理解できました。
これからも引き続きブログを書きアウトプットしていこうと思います。

参考

Qiita記事多数あり:「React useState 配列 更新」などで検索しました

3
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
3
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?