跳至主要内容

可序列化中间件

一个自定义中间件,用于检测状态或分派的 action 中是否包含任何不可序列化的值,其模型来自 redux-immutable-state-invariant。任何检测到的不可序列化值都将记录到控制台。

此中间件默认情况下由 configureStoregetDefaultMiddleware 添加到商店。

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

选项

interface SerializableStateInvariantMiddlewareOptions {
/**
* The function to check if a value is considered serializable. This
* function is applied recursively to every value contained in the
* state. Defaults to `isPlain()`.
*/
isSerializable?: (value: any) => boolean
/**
* The function that will be used to retrieve entries from each
* value. If unspecified, `Object.entries` will be used. Defaults
* to `undefined`.
*/
getEntries?: (value: any) => [string, any][]

/**
* An array of action types to ignore when checking for serializability.
* Defaults to []
*/
ignoredActions?: string[]

/**
* An array of dot-separated path strings or regular expressions to ignore
* when checking for serializability, Defaults to
* ['meta.arg', 'meta.baseQueryMeta']
*/
ignoredActionPaths?: (string | RegExp)[]

/**
* An array of dot-separated path strings or regular expressions to ignore
* when checking for serializability, Defaults to []
*/
ignoredPaths?: (string | RegExp)[]
/**
* Execution time warning threshold. If the middleware takes longer
* than `warnAfter` ms, a warning will be displayed in the console.
* Defaults to 32ms.
*/
warnAfter?: number

/**
* Opt out of checking state. When set to `true`, other state-related params will be ignored.
*/
ignoreState?: boolean

/**
* Opt out of checking actions. When set to `true`, other action-related params will be ignored.
*/
ignoreActions?: boolean
}

导出

createSerializableStateInvariantMiddleware

使用给定的选项创建可序列化检查中间件的实例。

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

示例

import { Iterable } from 'immutable'
import {
configureStore,
createSerializableStateInvariantMiddleware,
isPlain,
Tuple,
} from '@reduxjs/toolkit'
import reducer from './reducer'

// Augment middleware to consider Immutable.JS iterables serializable
const isSerializable = (value: any) =>
Iterable.isIterable(value) || isPlain(value)

const getEntries = (value: any) =>
Iterable.isIterable(value) ? value.entries() : Object.entries(value)

const serializableMiddleware = createSerializableStateInvariantMiddleware({
isSerializable,
getEntries,
})

const store = configureStore({
reducer,
middleware: () => new Tuple(serializableMiddleware),
})

isPlain

检查给定值是否被认为是“普通值”。

当前实现为

import isPlainObject from './isPlainObject'

export function isPlain(val: any) {
return (
typeof val === 'undefined' ||
val === null ||
typeof val === 'string' ||
typeof val === 'boolean' ||
typeof val === 'number' ||
Array.isArray(val) ||
isPlainObject(val)
)
}

这将接受所有标准的 JS 对象、数组和基本类型,但对于Dates、Maps 和其他类似的类实例将返回 false。