24
19

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 5 years have passed since last update.

this.setState()とuseState()で連想配列の一部だけ変更したい

Last updated at Posted at 2019-07-05

したいこと

Reactで連想配列のstate内にある項目を一部分だけ変更したい。
state = { a: array.a, b: array.b }のようにしてもいいが、配列の中身が多すぎるとすっきりしたコードにならない。

試したけどうまくいかなかった方法

this.setState({ array.a: newA });

→ ナメすぎました。笑

解決策

うまくいった方法

this.setState({ array: { a: newA } });

これだけでできました。

多次元配列の場合はシンプルに

this.setState({ array1: { array2: { a: newA } } });

でいけます。

Hooksを使う場合

ついでにHooksのuseStateを使う場合も試しました

const [stateOfArray, setStateOfArray] = useState({});

setStateOfArray(state => ({ ...state, a: newA }));

これでstateOfArray配列にあるa要素が変更されました。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?