typescript - 使用 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)
);
解决方案
我认为你没有正确地调度东西......你在没有通过商店的情况下调用你的动作。
如果您直接调用该操作,您将返回:
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
您可以调用它,它会正确调用您的操作并返回承诺。
推荐阅读
- php - PHP 错误:count() throws 参数必须是数组或实现 Countable 的对象
- selenium - DevToolsActivePort 文件不存在 Selenium Python
- javascript - 注释掉 `alert` 停止函数执行
- css - 当我们单击特定选项卡时如何显示引导卡主体数据
- scala - 如何将日期分区动态附加到json文件scala spark中的字符串
- javascript - 我需要创建一个组件来显示我的导航菜单吗?
- sql - 在我的选择列列表中将数据类型 nvarchar 转换为数字时出错
- javascript - JS:如果沿嵌套字典路径为空,则返回默认值
- json - 将嵌套的 JSON 解析为 STRUCT 类型的 BQ 表
- python - 尽管我使用问号,但正则表达式匹配重复部分