LoginSignup
1
0

Redux Toolkit の使い方を理解したいのでまとめてみました。
Redux Toolkit とは状態管理するライブラリです。

通常のReduxよりコード量が減って簡単に管理出来ます。

ポイントさえ抑えておけば簡単に使えます。

Install

インストールは次の通りです。

npm Install
npm install @reduxjs/toolkit react-redux

index

一度追加したらほぼ編集しないと思います。該当の追加箇所をコピペしたらOK。

app/index.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { store } from './app/store' //追加
import { Provider } from 'react-redux' //追加

ReactDOM.render(
  <Provider store={store}> //追加 
    <App />
  </Provider>,
  document.getElementById('root')
)

Slice

xxxxxSlice.tsx でファイル名を保存することを推奨されている模様。
ここに状態管理したい処理を書いてあげます。

機能ごとでファイルを追加して処理を書いて下さい。
以下はカウントをする処理の内容です。
公式チュートリアルをほぼ参考にしています。

features/counter/counterSlice.tsx
import { createSlice } from '@reduxjs/toolkit'

interface InitialStateInterface {
  value: number,
}

const initialState : InitialStateInterface = {
  value: 0,
}

export const counterSlice = createSlice({
  name: 'counter', //名前をつけてあげる
  initialState,    //状態管理したい型を記述
  reducers: {
    increment: (state) => {
    // ここは主に加算の処理をする役割//
      state.value += 1
    },
    decrement: (state) => {
    // ここは主に減算の処理をする役割//  
      state.value -= 1
    },
    incrementByAmount: (
        state,
            action: {              
            payload: InitialStateInterface; //対応する型を宣言 
            type: number;
                }
    // action.payload.valueにデータを受け渡して処理をする //
      state.value += action.payload.value
    },
  },
})

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions

export default counterSlice.reducer

重要なのは・・・

  • increment //主に追加処理
  • decrement //主に減算・リセット処理
  • incrementByAmount //引数を渡してなんでもできる

上記に処理を追加する事です。この3つを使い分けしたら基本的にOKです。
payloadは後ほどCounterに記述する型と合わせて下さい。

store

Sliceを追加したら都度変更する必要があります。
Sliceをインポートして必要箇所(reducer)を追加してください。

app/store.tsx
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice' //同一ファイル名追加

export const store = configureStore({
  reducer: {
    counter: counterReducer, //追加
    //Sliceを追加したらこの行に都度追加する必要がある
    
  },
})

Counter

画面に表示する処理です。

Sliceで先程記述した3つの処理を使用して状態管理します。

  • dispatch(increment()) //主に追加処理
  • dispatch(decrement()) //主に減算・リセット処理
  • dispatch(incrementByAmount(引数:any)) //引数を渡してなんでもできる
features/counter/Counter.tsx
import React from 'react'
import { useSelector, useDispatch } from 'react-redux' //import
import { decrement, increment ,incrementByAmount } from './counterSlice' //import

export function Counter() {

  
  const count = useSelector((state) => state.counter.value) // Slice の name で宣言した文字指定すると数字が取得出来る
  const dispatch = useDispatch() //更新するのに必須

  interface InitialStateInterface {
    value: number,
  }


  const initialState : InitialStateInterface = {
  value: 10,
  }


  return (
    <div>
      <div>
        <button
          aria-label="Increment value"
          onClick={() => dispatch(increment())} //追加処理される
        >
          Increment
        </button>
        <span>{count}</span>
        <button
          aria-label="Decrement value"
          onClick={() => dispatch(decrement())} //減算処理される
        >
          Decrement
        </button>
        <button
          aria-label="incrementByAmount value"
          onClick={() => dispatch(incrementByAmount(initialState))} //引数で渡した数値が処理される
        >
          incrementByAmount
        </button>
      </div>
    </div>
  )
}

その他

それぞれの役割(store/state/action・・・など)がありますが、Redux Toolkit は要点さえ理解すれば簡単に使えるので、それぞれの解説は省きます。
詳しく知りたい方向けにリンクを貼っておきます。

今回参考にしたチュートリアルです。

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