LoginSignup
7
4

More than 3 years have passed since last update.

React の state を配列やオブジェクトにするときの変更方法

Posted at

はじめに

この記事は CodeChrysalis Advent Calendar 2019 の記事です。

@elia が投稿を試みたのですが、なぜかスパム扱いされるので代理で投稿します(英語だからか…?)。
Eliaはアメリカ人で私のイマーシブのクラスメイトです。卒業後はIoTの会社でPython+Djangoを使ったり、現在は医薬系の会社でReactを使ったりしているそうです。

Get started!

This article describes how to do some simple cases for updating arrays and objects on events.
この記事ではイベントが発火したときにstateの配列やオブジェクトを変更する初心者向けのシンプルなケースを紹介します。

A common feature is updating a string based on an input.
A code snippet below to do that is:

よくあるのはインプットに基づいて文字列のstateを変更するものですね。コードスニペットは以下です。

const App = () => {
  const [theString, setTheString] = useState("");
  const handleChangeString = event => {
    setTheString(event.target.value);
  };
  return (
    <div className="App">
      String input: {theString}
      <input type="text" value={theString} onChange={handleChangeString} />
    </div>
  );
};

Now to show the case for an array, add this code snippet in the App component:
では配列のstateをどう変えるのか、componentのコードスニペットを紹介します。

spread operatorを使っています。

const [theArray, setTheArray] = useState([
    "",
    { color: "red", code: "" },
    "stan"
  ]);

const handleChangeArray = event => {
  event.persist();
  const name = event.target.name;
  const value = event.target.value;
  setTheArray(prev => ([...prev,  value ]));
};

return (
  <p>
    Array 
    <input
      type="text"
      name={theArray[theArray.length]}
      value={theArray[theArray.length]}
      onChange={handleChangeArray}
    />
  </p>
);

Now to show the case for an object, to update the key test and it’s value, add this code snippet in the App component:

ではstateをオブジェクトにした場合を見てみましょう。key というプロパティの値を変更してみます。コードスニペットは以下のとおりです。

こちらもspread operatorを使っています。

const [theObject, setTheObject] = useState({
  power: ["Lightning", "Strength"],
  name: { test: "", error: null }
});
const handleChangeObject = event => {
  event.persist();
  const name = event.target.name;
  const value = event.target.value;
  setTheObject(prev => ({
    ...prev,
    [name]: value
  }));
};
return (
  <p>
    Object
    <input
      type="text"
      name={theObject.name.test}
      value={theObject.name.test}
      onChange={handleChangeObject}
    />
  </p>
);

さいごに

To update nested arrays or objects, you can follow the similar process. Be careful about the nested properties since it can be confusing. This is the reason where something like useReducer separates the updates easier and is recommended.

もし配列やオブジェクトをネストしていても同じように考えます。ただしネストさせるととてもバグを生みやすくなるので注意してください。もしネストする場合やそもそもオブジェクトをstateで使わないといけない場合は、useReducerの出番になります。

7
4
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
7
4