インストール
デフォルトでReactのアプリケーションと同時にRedux Tool Kitのテンプレートを導入できます。
1 |
npx create-react-app . --template redux |
起動
1 |
npm start |
起動するとブラウザで画面が立ち上がり通常のcreate-react-appとは別のReduxによる簡易的な実装が行われたカウンターアプリが起動します。
- 入力値を単純にカウントを行う。
- 非同期で1秒後にカウントを行う。
Sliceの作成
xxxSlice.jsというファイルを作成します。RTKのcreateSliceという構文を使ってSliceを作成します。(xxxは名前)、なおsliceのアクションなどは定義したら全てexportします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import { createSlice } from '@reduxjs/toolkit'; export const xxxSlice = createSlice({ name: 'xxx', initialState: { value: 0 }, reducers: { increment(アクション名): (state,action) => { state.value += 1; }, }, }); // sliceで定義したactionは全てexportする。 export const { increment(アクション名) } = xxxSlice.actions; // useSelectorでコンポーネントから参照したいstateの値を代入 export const selectXXX = (state) => state.xxx.value; // reducerをexportする。 export default xxxSlice.reducer; |
ちなみに、createSliceとは?
reducerを作成するだけで自動的にaction typeや、action creatorも生成してくれます。つまり、従来のreduxでいうところのreducerとactionを一発で作成することができます。
reducersオブジェクト
reducersオブジェクトを作成したらキーから自動的にaction typeも生成されます。
Storeの作成
以下のようにconfigureStoreというReduxToolKitの関数でSlice同士を結合して一つのStoreを作ります。
1 2 3 4 5 6 7 8 |
import { configureStore } from '@reduxjs/toolkit'; import xxxReducer from '../features/xxx/xxxSlice'; export const store = configureStore({ reducer: { xxx: xxxReducer, }, }); |
Storeの登録
storeはindex.jsなどで以下のように登録します。
1 2 3 |
<Provider store={store}> <App /> </Provider> |
useSelector
storeから状態を参照したい場合はuseSelectorを使用します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import React from 'react'; import { useSelector } from 'react-redux'; import { エクスポートしたstate } from './xxxSlice'; const 使いたいコンポーネント名 = () => { const state名 = useSelector(エクスポートしたstate); return ( <> stateを使った処理 </> ); }; export default 使いたいコンポーネント名; |
useDispatch
Storeのアクションを呼び出したい時はuseDispatchを使用します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import React from 'react'; import { useDispatch } from 'react-redux'; import { アクション名 } from './xxxSlice'; const コンポーネント名 = () => { const dispatch = useDispatch(); return ( <div> <button onClick={() => dispatch(アクション名())}>アクション</button> </div> ); }; export default コンポーネント名; |
この記事へのコメントはありません。