【问题标题】:Custom middleware causes a circular reference in redux自定义中间件导致 redux 中的循环引用
【发布时间】:2021-09-14 12:17:07
【问题描述】:

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

https://redux.js.org/usage/usage-with-typescript#type-checking-middleware

但是,我在使用自定义中间件时遇到了麻烦。这是导致我出错的最小化和提取代码。

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' 隐式具有类型'any',因为它没有类型注释,并且在其自己的初始化程序中直接或间接引用。

【问题讨论】:

    标签: typescript redux redux-middleware


    【解决方案1】:

    在这种情况下,您将不得不以某种方式打破循环。

    这里最简单的方法是

    export type RootState = ReturnType<typeof customReducer>
    

    编辑:我认为您的初始代码是 reducer: customReducer

    使用给定的代码将无法工作 - 您需要在创建商店之前拆分该减速器的创建:

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

    【讨论】:

    • 嗯,首先有更多的reducer,而不仅仅是customReducer。我只是做了一个小例子。其次,如果我选择其中一个它不起作用。现在,当我添加 customMiddleware 时,它​​会抛出没有匹配的重载。
    • 编辑了答案
    • 嗯,有道理。如果我尝试这个,我会在前面得到错误。 '() => Middleware>' 类型的参数不可分配给'Middleware>' 类型的参数以及'() = > Middleware>' 不能分配给类型为“readonly Middleware>[]'的参数\
    • 我尝试将 export const customMiddleware = (): Middleware&lt;{}, RootState&gt; 更改为 export const customMiddleware = (): Middleware&lt;{}, RootState, Dispatch&lt;AnyAction&gt;&gt;
    【解决方案2】:

    啊,好吧,我想通了。问题在于我如何定义我的 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())
    

    我太傻了……

    编辑:也需要使用根减速器类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2018-04-10
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      相关资源
      最近更新 更多