py-py’s blog

何か書くよ

Redux メモ

Reduxはコンポーネントが大きくなった際に状態を管理する

格納先(一例)
src/actions/xxxx.js

  • reducer
    actionが発生した際に、そのactionに組み込まれたタイプに応じて状態をどう変化させるのか定義する

以下をインストールする

npm install redux
npm install react-redux

以下のようなactionを作る。
actions/index.js

export const INCREMENT = 'INCREMENT'
// action関数を設定
export const increment = () => {
    return {
        type: INCREMENT
    }
}

以下のファイルをつくる。これはアプリケーション内でのreducerを管理するファイルとなる
src/reducers/index.js

import { combineReducers } from "redux"; // 結合する関数をインポート
import application_name from "../application_name"

// 一つに管理
export default combineReducers(
  {
    application_name,
  }
)

reducerファイルを作る
src/reducers/application_name.js

// 
import { INCREMENT, DECREMENT} from "../application_name";

// 状態の初期値を設定
const initialState = { value: 0}

export default (state=initialState, action) => {
    // actionのタイプに応じて処理を帰る
    switch (action.type) {
        case INCREMENT:
            return { value: state.value + 1}
        default:
            return state
    }

}