自定义中间件导致redux中出现循环引用



我正在尝试使用提供的文档将redux项目转换为typescript:

https://redux.js.org/usage/usage-with-typescript#type-检查中间件

然而,我在使用自定义中间件时遇到了问题。这是最小化和提取的代码,它会给我带来错误

store.ts:

import { configureStore } from '@reduxjs/toolkit';
import reducer from './customReducer';
import { customMiddleware } from "./customMiddleware";
const store = configureStore({
reducer: {
custom: customReducer
},
middleware: getDefaultMiddleware => getDefaultMiddleware().prepend(customMiddleware)
})
export type RootState = ReturnType<typeof store.getState>
export default store

customMiddleware.ts:

import { Middleware } from 'redux';
import { RootState } from './store';
export const customMiddleware = (): Middleware<{}, RootState> => {
return store => next => action => {
return next(action);
}
}

这会导致多条错误消息:关于const store = configur...:

"store"隐式具有类型"any",因为它没有类型批注,并且在其自身的初始值设定项中被直接或间接引用。

关于RootState导出:

类型别名"RootState"循环引用自身。

关于customMiddleware导出:

"customMiddleware"隐式具有类型"any",因为它没有类型批注,并且在其自身的初始值设定项中被直接或间接引用。

在这种情况下,您必须以某种方式打破这个圆圈。

这里最简单的方法是

export type RootState = ReturnType<typeof customReducer>

编辑:我想你在这里的初始代码是reducer: customReducer

对于给定的代码,它不起作用——您需要在创建存储之前将reducer创建拆分:

const rootReducer = combineRecucers({
custom: customReducer
})
export type RootState = ReturnType<typeof rootReducer>
const store = configureStore({
reducer: rootReducer,
middleware: getDefaultMiddleware => getDefaultMiddleware().prepend(customMiddleware)
})

啊,好吧,我想明白了。问题在于我如何定义我的自定义中间件。文档简单地将导出定义为中间件:

export const customMiddleware: Middleware = store => next => action => {
return next(action);
}

但我将导出作为一个返回中间件的函数,因为在我的实际代码中有一些初始化:

export const customMiddleware = (): Middleware => {
return store => next => action => {
return next(action);
}
}

所以我只需要在准备时将其称为一个函数

middleware: getDefaultMiddleware => getDefaultMiddleware().prepend(customMiddleware())

我真傻…

EDIT:还需要使用根减少器类型。

最新更新