你可以简单地使用:redux-starter-kit 中的createReducer
微软的这个演示中也使用了它
一个实用函数,允许将 reducer 定义为从动作类型到处理这些动作类型的 case reducer 函数的映射。reducer 的初始状态作为第一个参数传递。
每个 case reducer 的主体都被隐式地封装在对 immer 库中的 producer() 的调用中。这意味着除了返回一个新的状态对象之外,您还可以直接改变传入的状态对象;然后,这些突变将自动有效地翻译成副本,为您提供便利和不变性。
@param initialState — reducer 要返回的初始状态。
@param actionsMap — 从动作类型到特定于动作类型的案例缩减器的映射。
用法
export const LocalStorageReducer = createReducer<Store['localStorage']>(
new LocalStorage(), // <= where you define the init value of this state
{
storeLocalStorageInput(state, action) {
return state = {...state, [action.payload.item]: action.payload.value};
},
clearLocalStorageInput(state, action) {
return state = new LocalStorage();
},
}
);
export const reducer = combineReducers({
localStorage: LocalStorageReducer,
...
类型createReducer
(alias) createReducer<LocalStorage, CaseReducers<LocalStorage, any>>(initialState: LocalStorage, actionsMap: CaseReducers<LocalStorage, any>): Reducer<LocalStorage, AnyAction>
import createReducer
状态样本
export class LocalStorage {
/**
* Editing plan id in planner pages
*/
planId: string | undefined;
/***
* Touched id list
*/
touchedIdList: Array<string>;
constructor() {
this.planId = undefined;
this.touchedIdList = Array<string>();
}
}
已经开发出通过库来完成这些事情的方法,在大多数情况下无需手动再次执行。