Redux Toolkit 模版

305 阅读1分钟

Redux Toolkit目前只有英文文档,英语较差的同学学习比较困难,这里分享一段Redux Toolkit的模版,大家可以直接拿去使用。

Redux 定义

uiStateSlice.ts

import { RootState } from '@models/store';
import { CaseReducer, createSlice, PayloadAction } from '@reduxjs/toolkit';

type UIState = {
  tabbar: number;
  backgroundColor: string;
};

/**
 * Reducers
 */
const updateTabarReducer: CaseReducer<UIState, PayloadAction<number>> = (
  state,
  action
) => {
  state.tabbar = action.payload;
};

const updateBackgroundColorReducer: CaseReducer<UIState, PayloadAction<string>> = (state, action) => {
  state.backgroundColor = action.payload;
};

/**
 * Slice
 */
const uiStateSlice = createSlice({
  name: 'uiState',
  initialState: {
    tabbar: 1,
    backgroundColor: 'pink',
  } as UIState,
  reducers: {
    updateTabar: updateTabarReducer,
    updateBackgroundColor: updateBackgroundColorReducer,
  },
});

/**
 * Selectors
 */
export const selectTabbar = (state: RootState) => state.uiState.tabbar;
export const selectBackgroundColor = (state: RootState) => state.uiState.backgroundColor;

/**
 * Actions
 */
export const { updateTabar, updateBackgroundColor } = uiStateSlice.actions;

export default uiStateSlice.reducer;

store.ts

import { configureStore } from '@reduxjs/toolkit';
import uiStateReducer from './modules/uiStateSlice';

const store = configureStore({
  reducer: {
    uiState: uiStateReducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

export default store;

获取 Redux 值

import { useSelector } from 'react-redux';
import { selectTabbar, selectBackgroundColor } from '@models/modules/uiStateSlice';

const tabbar = useSelector(selectTabbar);
const backgroundColor = useSelector(selectBackgroundColor);

修改 Redux 值

import { useDispatch } from 'react-redux';
import { updateTabar, updateBackgroundColor } from '@models/modules/uiStateSlice';

const dispatch = useDispatch();

dispatch(updateTabar(2));
dispatch(updateBackgroundColor('red'));