8
5

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.

reduxで配列操作する時のメモ

Posted at

目的

reduxで配列操作する時にサラッと確認したいメモです。
Reducerのみ

cardReducer.js
import {
    ADD_CARD,
    UPDATE_CARD,
    DELETE_CARD,
} from './cardTypes'

const initialState = {
    imageList: []
}

const cardReducer = (state = initialState, action) => {
    switch (action.type) {
        // 要素の追加
        case ADD_CARD:
            return {
                ...state,
                imageList: [...state.imageList, action.payload]
            }
        // 要素の更新
        // 要素のIDで更新対象を確定
        case UPDATE_CARD:
            return {
                ...state,
                imageList: state.imageList.map(el => el.id === action.payload.id ? action.payload : el)
            }
        // 要素の削除
        // 要素のIDで削除対象を確定
        case DELETE_CARD:
            return {
                ...state,
                imageList: state.imageList.filter((item) => item.id !== action.payload)
            }
        default: return state
    }
}

export default cardReducer
8
5
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
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?