19
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[React]useStateで定義したstateを更新したのに再レンダーされない件(object / 配列)

Posted at

少し詰まったので、書き記します。

newDataというstateを操作するfunction inputChange(e)を定義し、onChageイベントとして使ったが、再レンダーされず、入力値が変更できない。

js

    const [newData, setNewData] = useState({name:'', content:''});


    function inputChange(e){
        const key = e.target.name;
        const value = e.target.value;
        newData[key] = value;  // newDataの値を更新
        const data = newData  //setNewDataするため、dataを定義
        setNewData(data);
     }

コードは問題なさそうと思って悩んでいましたが、公式に答えがありました。

https://ja.reactjs.org/docs/hooks-reference.html#bailing-out-of-a-state-update
現在値と同じ値で更新を行った場合、React は子のレンダーや副作用の実行を回避して処理を終了します。(React は Object.is による比較アルゴリズム を使用します)

↓これで行けました

js

    function inputChange(e){
        const key = e.target.name;
        const value = e.target.value;
        newData[key] = value;
        let data = Object.assign({}, newData);  //オブジェクトを新しく作り直す必要がある
        setNewData(data);
     }

配列の場合はsplice()を使用して、新しい配列として、dataを定義します。

[学び] React.jsは公式が大事

19
9
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
19
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?