使用打字稿在Redux thunk中返回Promise

jfb*_*m22 6 typescript redux-thunk

我收到此打字稿错误: 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()
        )
      )
Run Code Online (Sandbox Code Playgroud)

动作创建者:

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

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

然后在我的组件中,我有一个prop接口:

interface IProps {
  anotherThunkAction: typeof anotherThunkAction;
}
Run Code Online (Sandbox Code Playgroud)

然后:

  componentWillMount() {
    this.props.anotherThunkAction().then(() => {console.log('hello world')})
  }
Run Code Online (Sandbox Code Playgroud)

连接我正在使用react-i18next的位置:

export default translate('manageInventory')(
  connect(
    mapStateToProps,
    {
      anotherThunkAction
    }
  )(ManageInventory)
);
Run Code Online (Sandbox Code Playgroud)

小智 7

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

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

ThunkAction<Promise<boolean>, IinitialState, undefined, any>
Run Code Online (Sandbox Code Playgroud)

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

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

type MyThunkDispatch = ThunkDispatch<IinitialState, undefined, any>

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

connect(null, mapDispatchToProps)(MyComponent)
Run Code Online (Sandbox Code Playgroud)

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