
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);
これで動いた。
興味深い・・・