使用打字稿在 Redux thunk 中返回承诺
Returning a promise in a Redux thunk with typescript
我收到这个打字稿错误: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);
}
}
然后在我的组件中有一个 prop 接口:
interface IProps {
anotherThunkAction: typeof anotherThunkAction;
}
然后:
componentWillMount() {
this.props.anotherThunkAction().then(() => {console.log('hello world')})
}
连接我正在使用 react-i18next 的地方:
export default translate('manageInventory')(
connect(
mapStateToProps,
{
anotherThunkAction
}
)(ManageInventory)
);
我认为你没有正确地发送东西...你在调用你的动作时没有将它传递给商店。
如果您直接调用操作,您将返回:
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)
这会将 anotherThunkAction
添加到 props
,您可以调用它,它会正确调用您的操作和 return 承诺。
我收到这个打字稿错误: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);
}
}
然后在我的组件中有一个 prop 接口:
interface IProps {
anotherThunkAction: typeof anotherThunkAction;
}
然后:
componentWillMount() {
this.props.anotherThunkAction().then(() => {console.log('hello world')})
}
连接我正在使用 react-i18next 的地方:
export default translate('manageInventory')(
connect(
mapStateToProps,
{
anotherThunkAction
}
)(ManageInventory)
);
我认为你没有正确地发送东西...你在调用你的动作时没有将它传递给商店。
如果您直接调用操作,您将返回:
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)
这会将 anotherThunkAction
添加到 props
,您可以调用它,它会正确调用您的操作和 return 承诺。