LoginSignup
0
0

More than 1 year has passed since last update.

React: オブジェクト内の配列の中にあるオブジェクトのステートを更新する

Posted at

Reactで、以下のようなオブジェクト内の配列の中にあるid: 2のオブジェクトのmemoを'ccc'に更新する方法。

{
    id: 1,
    name: 'test',
    memos: [
      {
        id: 1,
        memo: 'aaa',
      },
      {
        id: 2,
        memo: 'bbb',
      },
    ],
  }
  • コード
import * as React from 'react';
import './style.css';

export default function App() {
  const [list, setList] = React.useState({
    id: 1,
    name: 'test',
    memos: [
      {
        id: 1,
        memo: 'aaa',
      },
      {
        id: 2,
        memo: 'bbb',
      },
    ],
  });

  const updateMemo = () => {
    setList((prev) => ({
      ...prev,
      memos: prev.memos.map((el, index) =>
        index === 1 ? { ...el, memo: 'ccc' } : el
      ),
    }));
  };

  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>Start editing to see some magic happen :)</p>
      {list.memos.map((el) => (
        <li>{el.memo}</li>
      ))}
      <button onClick={() => updateMemo()}>Update</button>
    </div>
  );
}
  • StackBlitzで実際に動かしてみる

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