【问题标题】:dispatch is still expecting an Action even when redux-thunk installed?即使安装了 redux-thunk,调度仍然期待一个动作?
【发布时间】:2019-06-23 20:50:45
【问题描述】:

我正在尝试在基于 TypeScript 的 React Native 项目中使用 redux-thunk。我的操作被定义为

export type Action<T> = {
  type: T,
  payload?: any
}

我的店铺定义为

import { applyMiddleware, createStore } from 'redux'
import { persistStore } from 'redux-persist'
import thunk from 'redux-thunk'

import logger from 'src/redux/middleware/logger'
import rootReducer from 'src/redux/reducers'

export const store = createStore(rootReducer, applyMiddleware(logger, thunk))
export const persistor = persistStore(store)

我的动作构造函数定义为

export const setRepeat = (repeat: Repeating) => (
  dispatch: Dispatch<Action>,
  getState: () => AppState
) =>
  dispatch<Action>({
    payload: repeat,
    type: actionTypes.SET_REPEAT,
  })

Repeating 是一个简单的枚举:

export enum Repeating {
  All = 'all',
  None = 'none',
  Single = 'single',
}

当我尝试用

发送这个动作时
store.dispatch(setRepeat('all' as Repeating))

我收到此错误

TS2345: Property 'type' is missing in type '(dispatch: Dispatch<Action<string>>, getState: () => AppState) => Action<string>' but required in type 'Action<string>'.

据我所知,这意味着setRepeat 正在返回一个函数(这是有道理的,这就是它的定义)。但是store.dispatch 并不期待像 redux-thunk 这样的函数允许并且仍然期待 Action

我似乎找不到任何解释为什么 thunk 在这里没有提供正确的类型,或者我需要做些什么来纠正这个问题。

  • 反应原生:0.57.7
  • redux:4.0.1
  • react-redux: 6.0.0
  • redux-thunk:2.3.0

【问题讨论】:

  • 能否提供Repeating接口?我知道出了什么问题,但需要该代码来确认,谢谢。
  • 是的,我把它加进去了。

标签: typescript react-native redux-thunk


【解决方案1】:

This issue has been brought up on github

总而言之,您需要添加类型:

const store = createStore(
rootReducer,
applyMiddleware(
    thunk as ThunkMiddleware<IState, Actions>, // this is crucial
));

下面是原始答案

这里的问题是dispatch 采用Action&lt;T&gt; 的类型,该类型具有type 属性,但您向它发送了一个函数,而函数没有类型。请注意,setRepeat 是一个返回另一个函数的函数。

store.dispatch(setRepeat('all' as Repeating)(dispatcherInstance,getStateFunction))

我需要查看更多您的代码,但似乎您的处理方式有点错误。

【讨论】:

  • 是的。 redux-thunk 添加了一个中间件,以便动作创建者可以返回一个函数来进行计算,然后再调度(或不调度)。问题是store.dispatch 似乎没有考虑到这种变化的类型签名。我的问题是“这是我的错还是 redux-thunk 的错,无论哪种方式,我该怎么办?”
  • 您已将 Dispatch 键入为 Action 类型,但传入您的函数 dispatcherInstance 的调度实例不是 Action 类型。 Thunk 在这里没有那种类型:github.com/reduxjs/redux-thunk/blob/master/src/index.js#L2 看到这个已关闭的问题github.com/reduxjs/redux-thunk/issues/103
猜你喜欢
  • 2018-09-28
  • 2020-01-30
  • 2019-11-12
  • 2017-04-18
  • 2023-03-23
  • 2018-05-21
  • 2020-03-06
  • 2017-05-25
  • 2020-08-18
相关资源
最近更新 更多