12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React学習ログ No.13

Posted at

React(JavaScriptメモ):分割代入とスプレッド構文

1. 分割代入

目的

配列やオブジェクトから必要な値を個別の変数として抽出
コードを簡潔に

応用テクニック

項目 構文 詳細
デフォルト値 { key = defaultValue } = obj 値が存在しない場合に備えて初期値を設定できる。propsの省略時設定で便利
リネーム { key: newName } = obj 変数名が既存のものと競合する場合などに名前を変更できる
// 1. デフォルト値
const settings = { theme: 'light' };
// dataが存在しない場合、defaultPage=10 になる
const { data, page = 10 } = settings; // data=undefined, page=10

// 2. リネーム
const user = { id: 100, name: 'Alice' };
// idを userId として使う
const { id: userId, name } = user; // userId=100, name='Alice'

Reactでの必須パターン

構文 目的
配列 useStateの戻り値を受け取り const [count, setCount] = useState(0);
オブジェクト propsから値を取り出し const MyComponent = ({ name, age }) => { /* ... */ };

2. スプレッド構文

目的

配列やオブジェクトを展開・コピー・結合
不変性(Immutability)を守った状態更新に必須

応用テクニック:残余プロパティ

分割代入と同時に使用し、残りのすべてのプロパティを新しいオブジェクトにまとめることができる。Reactで不要なpropsを除外して子コンポーネントに渡す際などに役立つ

const userDetails = { 
  id: 1, 
  name: 'Taro', 
  email: 't@example.com',
  role: 'admin' 
};

// idとnameだけを取り出し、残りをotherInfoにまとめる
const { id, name, ...otherInfo } = userDetails;

// id=1, name='Taro'
// otherInfo = { email: 't@example.com', role: 'admin' }

Reactでの重要パターン:不変なデータの更新

【最重要】 Reactの状態(State)は直接変更せず
スプレッド構文でコピーしてから変更する。

a. オブジェクトの入れ子になった状態の更新

複雑なステートを扱う際、
ネストされたオブジェクトも不変性を守りながら更新する必要がある

const state = {
  user: { id: 1, name: 'Alice', address: { city: 'Tokyo' } }
};

// address.city を更新する例
const newState = {
  ...state, // stateをコピー
  user: {
    ...state.user, // state.userをコピー
    address: {
      ...state.user.address, // state.user.addressをコピー
      city: 'Osaka' // cityのみ更新
    }
  }
};
// どの階層でも古いオブジェクトを参照せず、新しいオブジェクトを生成している

b. 配列の要素の更新(リスト内の項目更新)

mapとスプレッド構文を組み合わせ、リスト内の特定の要素だけを不変的に更新する

const todos = [
  { id: 1, text: 'A', completed: false },
  { id: 2, text: 'B', completed: false },
];

const newTodos = todos.map(todo => {
  if (todo.id === 1) {
    // ID=1 の要素だけ新しいオブジェクトを生成して更新
    return { ...todo, completed: true }; 
  }
  return todo; // それ以外はそのまま返す
});
// newTodos は ID=1 の completed が true になった新しい配列
12
2
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
12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?