Alg*_*dyz 7 typescript redux redux-middleware
我正在尝试使用提供的文档将 redux 项目转换为打字稿:
https://redux.js.org/usage/usage-with-typescript#type-checking-middleware
但是我在使用自定义中间件时遇到了麻烦。这是导致我出错的最小化和提取的代码。
商店.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
Run Code Online (Sandbox Code Playgroud)
自定义中间件.ts:
import { Middleware } from 'redux';
import { RootState } from './store';
export const customMiddleware = (): Middleware<{}, RootState> => {
return store => next => action => {
return next(action);
}
}
Run Code Online (Sandbox Code Playgroud)
这会导致几条错误消息: on const store = configur...:
“store”隐式具有类型“any”,因为它没有类型注释,并且在其自己的初始值设定项中直接或间接引用。
关于 RootState 导出:
类型别名“RootState”循环引用自身。
关于自定义中间件导出:
“customMiddleware”隐式具有“any”类型,因为它没有类型注释,并且在其自己的初始值设定项中直接或间接引用。
在这种情况下,你就必须以某种方式打破这个循环。
这里最简单的方法是
export type RootState = ReturnType<typeof customReducer>
Run Code Online (Sandbox Code Playgroud)
编辑:我认为你的初始代码是 reducer: customReducer
使用给定的代码它将无法工作 - 您需要在创建商店之前拆分该减速器创建:
const rootReducer = combineRecucers({
custom: customReducer
})
export type RootState = ReturnType<typeof rootReducer>
const store = configureStore({
reducer: rootReducer,
middleware: getDefaultMiddleware => getDefaultMiddleware().prepend(customMiddleware)
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1612 次 |
| 最近记录: |