LoginSignup
0
0

More than 1 year has passed since last update.

React + Reduxを基本からまとめてみた【2】【Reducers】

Last updated at Posted at 2021-10-04

Fluxフロー図

flux_flow.png

Reducersとは

stateの変更を管理する役割を持っている

Reducersの役割

Actionsからデータを受け取り、Storeのstateをどう変更するのかを決める
⇨ Store内のstate(状態)の管理人

initialStateを作ろう

  • Storeの初期状態
  • アプリに必要なstateを全て記述
  • exportしておく
initialState.js
//src/reducks/store/initialState.js
const initialState = {
   products: {

   },
   users: {
       isSignedIn: false,
       uid: "",
       username: ""
  }
};
export default initialState

Reducersの書き方(1)

reducers.js
//src/reducks/users/reducers.js
import * as Actions from './actions'
import initialState from '../store/initialState'

① actionファイル内のモジュールを全てimport (Actionsという名前を付ける)

② initialStateをimport

Reducersの書き方(2)

reducers.js
//src/reducks/users/reducers.js
import * as Actions from './actions'
import initialState from '../store/initialState'

export const UsersReducer = (state = initialState.users, action)=> {
//                   第一引数にstate   第二引数にactionがreturnした値
//Actionsのtypeに応じてstateをどう変更するか決める
switch (action.type) {
   case Actions.SIGN_IN:
     return {
     ...state,
        ...action.payload
   }
   default:
        return state
    }
}
スプレッド構文とは
⇨ 配列やオブジェクトの要素を展開する
spred:広げる、開く
sample.js
const payload = {
    uid: '00000',
    username:'torahack'
}
console.log({...payload})
//{uid: '00000', username: 'torahack'}

//Merge Objects
const state = {
  isSignedIn: false,
  uid: "0",
  username: "fuga"
}
console.log({...state, ...payload})
// {isSignedIn: false, uid: "1", username: "hoge"}

参考サイト

日本一わかりやすいReact-Redux入門#5...Reducersの作り方とスプレッド構文の使い方
React- Redux 入門

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