使用 redux-thunk 的 ConnectedProps 获取正确的调度类型
Get correct dispatch type using ConnectedProps with redux-thunk
根据标题,我正在使用 Redux-Toolkit & Typescript。特别是,我正尝试按照 redux docs 中的建议使用 ConnectedProps。不幸的是,它似乎没有得到正确的调度类型(特别是,它认为它具有正常的调度类型而不是 ThunkDispatch)。
有什么建议吗?目前我是:
(1) 使用自定义 'useThunkDispatch' 挂钩。但这引入了我真的不想要的额外行+导入。
(2) 使用 'mapDispatch' 的函数版本,将我的调度明确键入为 ThunkDispatch(或 AppDispatch,如 redux toolkit docs
代码沙箱: https://codesandbox.io/s/connectedprops-typing-for-thunk-uyplw
根据您的评论,来自 connect
的 dispatch
的显式使用实际上是这里的问题。
因为您的 Redux 商店是与使用该商店的 React 组件分开定义的,所以它们无法知道您在创建商店时可能 使用了哪些自定义项。具体对于 TS,connect
无法知道您的商店应用了 thunk 中间件,因此应该将 dispatch
属性键入 ThunkDispatch
而不是 Dispatch
。
这就是我们强烈建议将 the "object shorthand" form of mapDispatch
与 connect
一起使用的原因之一,因为这样您的组件就永远不必知道差异。
如果您真的想在您的组件中显式引用 dispatch
,您有几个不同的选择:
- 切换到使用 the React-Redux hooks API and declare the type of
dispatch
as received from useDispatch
- 将the function form of
mapDispatch
与connect
一起使用,并显式声明dispatch
的类型作为参数
就个人而言,我建议使用钩子。
根据标题,我正在使用 Redux-Toolkit & Typescript。特别是,我正尝试按照 redux docs 中的建议使用 ConnectedProps。不幸的是,它似乎没有得到正确的调度类型(特别是,它认为它具有正常的调度类型而不是 ThunkDispatch)。
有什么建议吗?目前我是:
(1) 使用自定义 'useThunkDispatch' 挂钩。但这引入了我真的不想要的额外行+导入。
(2) 使用 'mapDispatch' 的函数版本,将我的调度明确键入为 ThunkDispatch(或 AppDispatch,如 redux toolkit docs
代码沙箱: https://codesandbox.io/s/connectedprops-typing-for-thunk-uyplw
根据您的评论,来自 connect
的 dispatch
的显式使用实际上是这里的问题。
因为您的 Redux 商店是与使用该商店的 React 组件分开定义的,所以它们无法知道您在创建商店时可能 使用了哪些自定义项。具体对于 TS,connect
无法知道您的商店应用了 thunk 中间件,因此应该将 dispatch
属性键入 ThunkDispatch
而不是 Dispatch
。
这就是我们强烈建议将 the "object shorthand" form of mapDispatch
与 connect
一起使用的原因之一,因为这样您的组件就永远不必知道差异。
如果您真的想在您的组件中显式引用 dispatch
,您有几个不同的选择:
- 切换到使用 the React-Redux hooks API and declare the type of
dispatch
as received fromuseDispatch
- 将the function form of
mapDispatch
与connect
一起使用,并显式声明dispatch
的类型作为参数
就个人而言,我建议使用钩子。