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?

【useState】オブジェクトの中のオブジェクトを更新する

Last updated at Posted at 2022-07-02

特定のプロパティを更新する

こういったオブジェクトがあるとする

  const [obj, setObj] = useState({
    gender: "",
    age: 20,
    height: 170,
  });

特定のプロパティを更新する

setObj({ ...obj, gender: "" });
失敗例
setObj({  gender: "" });

こうかくとすべて更新されてしまい、オブジェクトは

{
  gender:""
}

となってしまう。
そもそも TypeScript を使用していれば、エラーをはいてくれると思う。

オブジェクトの中のオブジェクトのプロパティを更新する

次にこのようなオブジェクトがあるとする

const [data, setData] = useState({
    title: "国名",
    countries: {
      values: ["日本","アメリカ"]
    }
});

この values の中を更新するには

setData({ ...data, countries: { values: ["韓国", "中国"] } });

さらにネストしていたら、更新関数もネスとさせてやればいい

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?