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

「Error: Cannot modify local variables after render completes」の解決方法

1
Posted at

はじめに

Reactでローカル変数でデータを保持しようとしたらエラーが出た。

問題

Error: Cannot modify local variables after render completes

以下のようにstateが更新されようとしている中でtimeListが書き換えられているのが問題らしい。

  const handleClick = () => {
    if (title == "" || time == 0 || time == "") {
      setError("入力されていない項目があります");
    } else {
      setRecords([...records, { title: title, time: time }]);

      // ここ
      timeList.push(time)
      
      setTitle("");
      setTime(0);
      setError("");
    }
  };

解決方法

レンダリングされても保持しておきたいデータはstateで管理する。

setTimeList([...timeList, time]); 

ローカル変数: レンダリングのたびに「毎回、初期値に戻る(初期化される)」
State: レンダリングを跨いでも「Reactが値を覚えておいてくれる」

おわりに

今までuseStateをどういう場面で使うのかを理解せず感覚で使っていた。これからは保持しておきたいならstate、レンダリング後にリセットされて新しく定義するのでいいならローカル変数を使うことにする。

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