Redux Toolkit 是 Redux 的官方工具集,旨在简化 Redux 的使用。如果你想在多个地方运行相同的 Redux 代码,可以考虑以下几种方法:
虽然 Redux 通常建议使用单一的全局 Store,但在某些情况下,你可能需要多个 Store。Redux Toolkit 并没有直接支持多个 Store,但你可以通过创建多个独立的 Redux 应用来实现这一点。
// store1.js
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers';
const store1 = configureStore({
reducer: rootReducer,
});
export default store1;
// store2.js
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers';
const store2 = configureStore({
reducer: rootReducer,
});
export default store2;
如果你希望在同一个 Store 中运行相同的代码,但有不同的状态管理需求,可以使用多个 Reducer。
// reducers.js
import { combineReducers } from 'redux';
import commonReducer from './commonReducer';
const rootReducer = combineReducers({
case1: commonReducer,
case2: commonReducer,
});
export default rootReducer;
Redux Toolkit 的 createSlice
可以帮助你创建多个 Slice,每个 Slice 都有自己的 Reducer 和 Actions。
// slices/commonSlice.js
import { createSlice } from '@reduxjs/toolkit';
const commonSlice = createSlice({
name: 'common',
initialState: { value: 0 },
reducers: {
increment: state => state.value + 1,
decrement: state => state.value - 1,
},
});
export const { increment, decrement } = commonSlice.actions;
export default commonSlice.reducer;
// store.js
import { configureStore } from '@reduxjs/toolkit';
import commonReducer1 from './slices/commonSlice';
import commonReducer2 from './slices/commonSlice';
const store = configureStore({
reducer: {
case1: commonReducer1,
case2: commonReducer2,
},
});
export default store;
如果你希望在不同的组件或模块中使用相同的 Redux 逻辑,可以创建多个实例。
// commonSlice.js
import { createSlice } from '@reduxjs/toolkit';
export function createCommonSlice() {
return createSlice({
name: 'common',
initialState: { value: 0 },
reducers: {
increment: state => state.value + 1,
decrement: state => state.value - 1,
},
});
}
// case1Slice.js
import { createCommonSlice } from './commonSlice';
const case1Slice = createCommonSlice();
export const { increment: incrementCase1, decrement: decrementCase1 } = case1Slice.actions;
export default case1Slice.reducer;
// case2Slice.js
import { createCommonSlice } from './commonSlice';
const case2Slice = createCommonSlice();
export const { increment: incrementCase2, decrement: decrementCase2 } = case2Slice.actions;
export default case2Slice.reducer;
// store.js
import { configureStore } from '@reduxjs/toolkit';
import case1Reducer from './case1Slice';
import case2Reducer from './case2Slice';
const store = configureStore({
reducer: {
case1: case1Reducer,
case2: case2Reducer,
},
});
export default store;
通过以上方法,你可以在多个地方运行相同的 Redux 代码,并根据具体需求进行灵活配置。
领取专属 10元无门槛券
手把手带您无忧上云