首页 > 解决方案 > 使用 typescript 在 Redux thunk 中返回一个 Promise

问题描述

我收到此打字稿错误: Property 'then' does not exist on type 'ThunkAction<Promise<boolean>, IinitialState, undefined, any>'.

请帮忙!

我如何配置我的商店并包含类型:

    return createStore(
      rootReducer,
      intialState,
      require('redux-devtools-extension').composeWithDevTools(
        applyMiddleware(
          thunk as ThunkMiddleware<IinitialState, any>,
          require('redux-immutable-state-invariant').default()
        )
      )

动作创建者:

type ThunkResult<R> = ThunkAction<R, IinitialState, undefined, any>;

export function anotherThunkAction(): ThunkResult<Promise<boolean>> {
  return (dispatch, getState) => {
    return Promise.resolve(true);
  }
}

然后在我的组件中我有一个道具接口:

interface IProps {
  anotherThunkAction: typeof anotherThunkAction;
}

然后:

  componentWillMount() {
    this.props.anotherThunkAction().then(() => {console.log('hello world')})
  }

连接我使用 react-i18next 的地方:

export default translate('manageInventory')(
  connect(
    mapStateToProps,
    {
      anotherThunkAction
    }
  )(ManageInventory)
);

标签: typescriptredux-thunk

解决方案


我认为你没有正确地调度东西......你在没有通过商店的情况下调用你的动作。

如果您直接调用该操作,您将返回:

ThunkAction<Promise<boolean>, IinitialState, undefined, any>

正如 tsc 告诉你的那样,它没有then功能。当您运行某些东西时,dispatch它会ThunkResult<R>变成R

您还没有向商店展示您connect的组件 - 但我认为这就是问题所在。这是一个示例:

type MyThunkDispatch = ThunkDispatch<IinitialState, undefined, any>

const mapDispatchToProps = (dispatch: MyThunkDispatch) => ({
  anotherThunkAction: () => dispatch(anotherThunkAction())
})

connect(null, mapDispatchToProps)(MyComponent)

这将添加anotherThunkActionprops您可以调用它,它会正确调用您的操作并返回承诺。


推荐阅读