Action Creator 中间件
一个自定义中间件,用于检测是否错误地派发了 Action Creator,而不是在派发之前调用它。
一个常见的错误是调用 dispatch(actionCreator)
而不是 dispatch(actionCreator())
。这通常“有效”,因为 Action Creator 具有静态 type
属性,但会导致意外行为。
选项
export interface ActionCreatorInvariantMiddlewareOptions {
/**
* The function to identify whether a value is an action creator.
* The default checks for a function with a static type property and match method.
*/
isActionCreator?: (action: unknown) => action is Function & { type?: unknown }
}
导出
createActionCreatorInvariantMiddleware
使用给定选项创建 Action Creator 检查中间件的实例。
您很可能不需要自己调用它,因为 getDefaultMiddleware
已经这样做了。示例
- TypeScript
- JavaScript
import {
configureStore,
createActionCreatorInvariantMiddleware,
Tuple,
} from '@reduxjs/toolkit'
import reducer from './reducer'
// Augment middleware to consider all functions with a static type property to be action creators
const isActionCreator = (
action: unknown
): action is Function & { type: unknown } =>
typeof action === 'function' && 'type' in action
const actionCreatorMiddleware = createActionCreatorInvariantMiddleware({
isActionCreator,
})
const store = configureStore({
reducer,
middleware: () => new Tuple(actionCreatorMiddleware),
})
import {
configureStore,
createActionCreatorInvariantMiddleware,
Tuple,
} from '@reduxjs/toolkit'
import reducer from './reducer'
// Augment middleware to consider all functions with a static type property to be action creators
const isActionCreator = (action) =>
typeof action === 'function' && 'type' in action
const actionCreatorMiddleware = createActionCreatorInvariantMiddleware({
isActionCreator,
})
const store = configureStore({
reducer,
middleware: () => new Tuple(actionCreatorMiddleware),
})