122
70

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

[React] useStateをどう使うか(配列、オブジェクト)

Last updated at Posted at 2020-06-14

オブジェクトや配列に対して、useStateをどう使うか

Objectの分割代入を使う。
MDN:分割代入

オブジェクトの場合


const [member, setMember] = useState({ name: "", part: "" });

//オブジェクトを分解して、nameの値を更新する(分割代入)
setMember({ ...member, name: e.target.value });

//こう書くと、その時の他の値を消してしまう。この場合だと、partが消えてしまう
setMember({ name: e.target.value });
import React, { useState } from "react";

const Member = () => {
  const [member, setMember] = useState({ name: "", part: "" });

  return (
    <>
      <p>My name is {member.name}</p>
      <p>My part is {member.part}</p>
      <form action="">
        <div>
          <input
            type="text"
            value={member.name}
            onChange={(e) => {
              // オブジェクトを分解して、nameの部分だけ新しい値をセットする
              setMember({ ...member, name: e.target.value });
            }}
          />
        </div>
        <div>
          <input
            type="text"
            value={member.part}
            onChange={(e) => {
              // オブジェクトを分解して、partの部分だけ新しい値をセットする
              setMember({ ...member, part: e.target.value });
            }}
          />
        </div>
      </form>
    </>
  );
};

const App = () => {
  return (
    <>
      <Member />
    </>
  );
};

####配列の場合
同様に分割代入を利用する

const Members = () => {
  const [members, setMembers] = useState([]);

  const newMember = () => {
    setMembers([
      ...members,
      {
        id: members.length,
        name: Math.random() > 0.5 ? "猫派" : "犬派",
      },
    ]);
  };

  const deleteMember = (id) => {
    setMembers(members.filter((_, i) => i !== id))
  }

  return (
    <>
      <button onClick={newMember}>JoinMember</button>
      <ul>
        {members.map((member) => (
          <li key={member.id}>
            {member.name}
            <button onClick={() => deleteMember(member.id)}>削除</button>  
          </li>
        ))}
      </ul>
    </>
  );
};

const App = () => {
  return (
    <>
      <Members />
    </>
  );
};
122
70
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
122
70

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?