0
0

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

ReactのReducerメモ

0
Last updated at Posted at 2020-05-03

1.Reducerの記述

accountReducer.js
// ここからstate
const DEFAULT_STATE = {
  list: [],
  selected: new FAMILY({})
}

// ここからReducer
// 古いstateを取り出して、actionを受け取る
export default (state = DEFAULT_STATE, action) => {
 // actionのタイプによって振る舞いを変える
  switch (action.type) {
    case SET_ACCOUNT:
      return { ...state, me: action.payload }
    case SIGN_IN_ACCOUNT:
      return { ...state, me: action.payload.me, authToken: action.payload.authToken, isLoggedIn: true }
    case SIGN_OUT:
      return DEFAULT_STATE
    default:
      return state
  }
}

stateの中にはlist, selected, meなどの細分化されたstateがある。
actionがきっかけとなってこれらの更新を行うのがReducer

:point_up_tone1:例)車
Reducerがない: 車のガソリンが勝手に抜かれる、なくなる→困る
Reducerがある: 走るという行為(action)によってのみガソリンがへる

2.各ReducerをindexReducerにコンバインする

indexReducer.js
import family from './familyReducer'
import familyReducer from './familyReducer'

export default history =>
  combineReducers({
    router: connectRouter(history),
    account: persistReducer(authPersistConfig, account),
    app,
  })

こうすると以下で取ってこれる

const mapStateToProps{(family)}

PersistReducerは永続化

ブラウザにはローカルストレージというものがある
(whitelistという箱を使う)
→ブラウザにデータを保存するので、ページをリロードしたり、タブを消した時にもデータが引き継がれる(永続化される)

indexReducer.js
const authPersistConfig = {
  key: 'auth',
  storage: storage,
  whitelist: ['id', 'authToken'],  //ここ
}

メモ

オニオン型のアーキテクチャを理解する

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?