useStateで現在のステートをsetState(current => ({ …currentで取得できるのを初めて知った

ReduxのImmerの勉強をしていたら、こういうコードを見ました。

 

const [state, setState] = useState({
    id: 14,
    email: "stewie@familyguy.com",
    profile: {
      name: "Stewie Griffin",
      bio: "You know, the... the novel you've been working on",
      age:1
    }
  });
function changeBio(newBio) {
    setState(current => ({
      ...current,
      profile: {
        ...current.profile,
        bio: newBio
      }
    }));
  }

 

ん? useStateの現在の値って、

 

setState(current => ({ ...current

 

これで取れるのか?って思った。

 

詳しく仕組みをまだ理解しきれてないと思うんだけども、

 

とりあえず、動かしてみたら、

 

 

import React, { useState } from "react";
import ReactDOM from "react-dom";

function App() {
  const [state, setState] = useState({
    id: 14,
    email: "test@yahoo.co.jp",
    profile: {
      name: "Ryosuke",
      bio: "こんにちわ",
      age: 20
    }
  });
  return (
    <div>
      <h2>{state.profile.bio}</h2>
      <button
        onClick={() => {
          setState((current) => ({
            ...current,
            profile: {
              ...current.profile,
              bio: "bioを変えたよ"
            }
          }));
        }}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

 

これで動いた。

 

興味深い・・・

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です