跳至主要内容

不变性中间件

redux-immutable-state-invariant 中间件的移植版本,专门用于 Redux Toolkit。任何检测到的变异都将作为错误抛出。

此中间件默认情况下由 configureStoregetDefaultMiddleware 添加到存储中。

您可以通过将任何支持的选项作为 getDefaultMiddlewareimmutableCheck 值传递来自定义此中间件的行为。

选项

type IsImmutableFunc = (value: any) => boolean

interface ImmutableStateInvariantMiddlewareOptions {
/**
Callback function to check if a value is considered to be immutable.
This function is applied recursively to every value contained in the state.
The default implementation will return true for primitive types
(like numbers, strings, booleans, null and undefined).
*/
isImmutable?: IsImmutableFunc
/**
An array of dot-separated path strings or RegExps that match named nodes from
the root state to ignore when checking for immutability.
Defaults to undefined
*/
ignoredPaths?: (string | RegExp)[]
/** Print a warning if checks take longer than N ms. Default: 32ms */
warnAfter?: number
}

导出

createImmutableStateInvariantMiddleware

使用给定的选项创建不可变性检查中间件的实例。

您很可能不需要自己调用此方法,因为 getDefaultMiddleware 已经这样做了。

示例

// file: exampleSlice.ts
import { createSlice } from '@reduxjs/toolkit'

export const exampleSlice = createSlice({
name: 'example',
initialState: {
user: 'will track changes',
ignoredPath: 'single level',
ignoredNested: {
one: 'one',
two: 'two',
},
},
reducers: {},
})

export default exampleSlice.reducer


// file: store.ts
import {
configureStore,
createImmutableStateInvariantMiddleware,
Tuple,
} from '@reduxjs/toolkit'

import exampleSliceReducer from './exampleSlice'

const immutableInvariantMiddleware = createImmutableStateInvariantMiddleware({
ignoredPaths: ['ignoredPath', 'ignoredNested.one', 'ignoredNested.two'],
})

const store = configureStore({
reducer: exampleSliceReducer,
// Note that this will replace all default middleware
middleware: () => new Tuple(immutableInvariantMiddleware),
})

使用 getDetfaultMiddleware 在不移除所有其他中间件的情况下执行相同操作

import { configureStore } from '@reduxjs/toolkit'

import exampleSliceReducer from './exampleSlice'

const store = configureStore({
reducer: exampleSliceReducer,
// This replaces the original default middleware with the customized versions
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
immutableCheck: {
ignoredPaths: ['ignoredPath', 'ignoredNested.one', 'ignoredNested.two'],
},
}),
})

isImmutableDefault

"此值是否不可变?" 检查的默认实现。当前实现为

return (
typeof value !== 'object' || value === null || typeof value === 'undefined'
)

这将对原始类型(如数字、字符串、布尔值、null 和 undefined)返回 true