【发布时间】:2019-06-19 15:09:57
【问题描述】:
我在网上发现了类似的问题,但在通过store.dispatch() 调用redux-thunk Action 时没有解决方案。
我有以下action:
export class DBActions {
static startDatabase(): ThunkAction<Promise<void>, {}, IClientState, AnyAction> {
return async (dispatch: ThunkDispatch<{}, {}, AnyAction>, getState: () => IClientState): Promise<void> => {
return new Promise<void>((resolve) => {
dispatch(DBActions.connectDatabase())
setTimeout(() => {
let connection: (Connection | undefined) = getDBConnection(getState())
if (connection) {
dispatch(DBActions.getImports(connection))
resolve()
}
}, 2000)
})
}
}
}
当通过mapDispatchToProps 在组件中添加时,这可以正常工作,但在定义store 后直接在我的store.ts 中调用时不会出现问题。 store.dispatch(DBActions.startDatabase()) 导致:
TS2345: Argument of type 'ThunkAction<Promise<void>, {}, {}, AnyAction>' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type 'ThunkAction<Promise<void>, {}, {}, AnyAction>'.
感谢任何帮助和建议!
【问题讨论】:
-
乍一看,您的类型注释看起来是正确的。你可以尝试从'redux'输入
dispatch到Dispatch并通过dispatch<any>(DBActions.connectDatabase())调用的组合,或者保留dispatch的注释,但通过dispatch<AnyAction>(DBActions.connectDatabase())调用,甚至通过dispatch<ThunkAction<...>>(...)调用? -
哦,哇,你是对的。真的就是这么简单!
store.dispatch<any>(DBActions.startDatabase())工作 :) 非常感谢! -
store.dispatch<any>看起来像是 hack 而不是 IMO 的解决方案。你如何初始化商店?
标签: reactjs typescript redux react-redux redux-thunk