網站搜尋

typescript - 自訂中介軟體在 redux 中引起循環參考


我正在嘗試使用提供的文件將一個 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 導出時:

‘customMiddleware’ 隱含地具有類型 ‘any’,因為它沒有類型註解,並且在其自身的初始化器中直接或間接被引用。

答案#1

在那種情況下,你將不得不想辦法打破這個圈子。

這裡最簡單的方法是

export type RootState = ReturnType<typeof customReducer>

編輯:我認為你最初的程式碼是 reducer: customReducer

使用給定的程式碼它無法運作——你需要在建立 store 之前將那個 reducer 的建立過程拆開:

const rootReducer = combineRecucers({
        custom: customReducer
})

export type RootState = ReturnType<typeof rootReducer>

const store = configureStore({
    reducer: rootReducer,
    middleware: getDefaultMiddleware => getDefaultMiddleware().prepend(customMiddleware)

})

答案#2

啊,好的,我弄清楚了。問題出在我定義 customMiddleware 的方式。文檔只是將導出定義為 Middleware:

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())

我真是太傻了…

編輯:同時也需要使用一個根 reducer 類型。