1
2

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.

ReduxToolkitとcreateContext,useReducerを使ってProviderを作成しグローバルにstateの値を管理する

Last updated at Posted at 2021-04-13

はじめに

reactを使う中でStateの管理にProviderを作る事が多いため、忘れないようにメモ。
ReactとTypescriptで書いています。初心者のため、間違っているところもあるかもしれません。

目次

  1. インストール
  2. createSliceの作成
  3. ContextとProviderの作成
  4. 使い方

インストール

ターミナル
$ yarn add @reduxjs/toolkit react-redux
$ yarn add -D @types/react-redux

createSliceの作成

provider.tsx
import React,{createContext,useReducer} from 'react';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

//Stateのタイプを設定
export type KakeiboState = {
    detailPlan:Array<number>;
    sumDetailPlan:number;
    resultPlan:Array<number>;
    sumResultPlan:number;
}

//Stateの初期値を設定
const initialState:KakeiboState = {
    detailPlan :[...Array(5)].fill(0),
    sumDetailPlan :0,
    resultPlan:[...Array(5)].fill(0),
    sumResultPlan:0,
}

// createSliceでreducerとactionを同時に定義
const kakeiboSlice = createSlice({
    name: 'kakeibo',
    initialState,
    reducers: {
        setDetailPlan: (state, action: PayloadAction<Array<number>>) => {
            return{ 
          ...state,
          detailPlan: action.payload,
            }
        },
        setSumDetailPlan: (state, action: PayloadAction<number>) => {
            return{ 
          ...state,
          sumDetailPlan: action.payload,
            }
        },
        setResultPlan:(state,action:PayloadAction<Array<number>>) => {
            return{
                ...state,
                resultPlan:action.payload
            }
        },
        setSumResultPlan:(state,action:PayloadAction<number>) => { 
            return{
                ...state,
                sumResultPlan:action.payload
            }
        },
        setInitialState:() => ({
            ...initialState,
        })    
    },
})

//actionとしてエクスポートする
export const {
    setDetailPlan,
    setSumDetailPlan,
    setResultPlan,
    setSumResultPlan,
    setInitialState
} = kakeiboSlice.actions;

ContextとProviderの作成

provider.tsx

//Providerに使う型の設定
type KakeiboProviderValue = {
    kakeiboInfo:KakeiboState;
    kakeiboDispatch:React.Dispatch<PayloadAction<
        |number
        |Array<number>
        >
    >;
};

//コンテクストの作成
export const KakeiboContext = createContext({} as KakeiboProviderValue);

type KakeiboProviderProps = {
    children:React.ReactNode;
};

//useReducerを使ってProviderの作成
const KakeiboProvider:React.FC<KakeiboProviderProps> = (props:KakeiboProviderProps) => {
    const [kakeiboInfo,kakeiboDispatch] = useReducer(
        kakeiboSlice.reducer,initialState);

    return(
        <KakeiboContext.Provider value={{kakeiboInfo,kakeiboDispatch}}>
            {props.children}
        </KakeiboContext.Provider>
    );
};

export default KakeiboProvider

使い方

・Providerを使用したいファイルをProviderで挟みます。間にいくつ挟んでも大丈夫です。

App.tsx

import React from 'react';
import './App.css';
import Kakeibo from './kakeibo/Component/main';
import KakeiboProvider from '../src/kakeibo/Container/Provider/provider';

const App:React.FC = () => {
  return (
    <KakeiboProvider>
        <Kakeibo />
    </KakeiboProvider>
  );
}

export default App;


#### インポート文

Kakeibo.tsx
//useContextとProviderで作成したKakeiboContextをインポートします。
//stateの値を変更したい処置がある場合は、reducerに書いたものからインポートします。この場合はsetSumDetailPlanです。
import React,{useContext} from 'react'
import {KakeiboContext,setSumDetailPlan} from '../Provider/provider';

#### 使用する時

Kakeibo.tsx
//Providerで宣言したものを使います。
const {kakeiboInfo,kakeiboDispatch} = useContext(KakeiboContext);

//Providerから値を取得する時
conosle.log(kakeiboInfo.sumDetailPlan) //現在のstateに入っているsumDetailPlanの値が返される

//Providerを使ってstateを変化させる時
kakeiboDispatch(setSumDetailPlan(5)) //state中のsumDetailPlanに「5」が設定される

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?