LoginSignup
6
6

More than 5 years have passed since last update.

ReduxでネストしているStateの一部分だけを更新する(備忘録)

Last updated at Posted at 2018-03-16

Stateを小さい単位で更新したい時の、Reducerのreturn内の書き方

Reducerを分割するほどではない時にやる

いっつも忘れるので備忘

Example

レストランの注文管理システムだとして...

Stateの構造。各要素に個数を持ってるイメージ

  • foods
    • beef
    • chicken
  • drinks
    • coffee
    • tea
    • water
// @flow

type State = {
  foods: Foods,
  drinks: Drinks,
}

type Foods = {
  beef: number,
  chicken: number,
}

type Drinks = {
  coffee: number,
  tea: number,
  water: number,
}

注文情報をセットするSET_ORDERと、コーヒーの個数だけセットするSET_COFFEEがあるとする

// @flow

const setOrder = (order: State): Action => ({
  payload: order,
  type: "SET_ORDER",
})

const setCoffee = (count: number): Action => ({
  payload: count,
  type: "SET_COFFEE",
})

こんな感じ

SET_COFFEEのreturn内

// @flow

const orderReducer = (state: State = initialState, action: Action): State => {
  switch (action.type) {
    case "SET_ORDER":
      return action.payload
    case "SET_COFFEE":
      return {
        ...state,
        drinks: {
          ...state.drinks,
          coffee: action.payload,
        },
      }
    default:
      return state
  }
}

以上

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