如果您不想添加依赖项(某些项目无法承受),那么对于更轻量级的解决方案,我选择实现只需要几行代码的简单帮助程序。 This article 帮助我找到了简化一切的食物起点。
这里是一些示例 TypeScript 代码,您可以将其放入帮助文件中,然后用于更简洁地编写操作/reducer,而无需添加大量依赖项。
import { AnyAction } from 'redux'
// Helpers for creating actions, can use version with payload if all your actions have a payload parameter, or a more generic one
export type ActionFunction = (payload: any) => AnyAction
export type FunctionWithString<T extends Function> = T & string
export interface ActionWithPayload<T = any> extends AnyAction {
payload: T
}
export type ActionCreator<T = any> = FunctionWithString<(payload: T) => ActionWithPayload<T>>
export function createPayloadAction<T>(name: string): ActionCreator<T> {
const actionCreator = (payload: T) => ({
type: name,
payload,
})
actionCreator.toString = () => name
return (actionCreator as any) as ActionCreator<T>
}
export function createAction<T>(name: string, actionFunction: ActionFunction): ActionCreator<T> {
const actionCreator = (payload: T) => ({
type: name,
payload: actionFunction(payload),
})
actionCreator.toString = () => name
return (actionCreator as any) as ActionCreator<T>
}
// The shape of your reducer functions, makes it easier to deal with having all reducers deal with the same payload-based action format
export type MyReducer<S, A = any> = (state: S, payload: A) => S
export interface ReducersMap<S> {
[key: string]: MyReducer<S>
}
export function createReducer<S>(reducers: ReducersMap<S>, defaultState: S) {
return (state: S, action: ActionWithPayload) => {
if (!state) {
return defaultState
}
const reducer = reducers[action.type]
if (reducer) {
return reducer(state, action.payload)
}
return state
}
}
// Common use case helpers for reducers
type KeyValueState<T> = { [key: string]: T }
// Updates a specific value key in a reducer that is shaped like a key-value object
export function keyValueUpdateReducer<T>(
state: KeyValueState<T>,
id: string,
value: Partial<T>,
): KeyValueState<T> {
return {
...state,
[id]: {
...state[id],
...value,
},
}
}
// Update a specific value in a reducer that is shaped like a key-value object
export function keyValueSetReducer<T>(
state: KeyValueState<T>,
id: string,
value: T,
): KeyValueState<T> {
return {
...state,
[id]: value,
}
}
使用示例:
action
import { createPayloadAction } from './helpers'
export interface SetAThingPayload {
id: string
thing: any
}
export const setAThing = createPayloadAction<SetAThingPayload('SET_A_THING')
reducer
import { createReducer, keyValueSetReducer, keyValueUpdateReducer } from './helpers'
import { setAThing } from './actions'
export const thingsReducer = createReducer<MyAppState>(
{
[setAThing]: (state, { id, thing }) => keyValueSetReducer(state, id, thing),
},
{},
)