【发布时间】:2018-08-31 15:43:24
【问题描述】:
我有一个 redux thunk 操作,它获取一些数据,然后分派一些操作(此处的代码中未显示,但您可以在下面的演示链接中找到它)
export const fetchPosts = (id: string) => (dispatch: Dispatch<TActions>) => {
return fetch('http://example.com').then(
response => {
return response.json().then(json => {
return "Success message";
});
},
err => {
throw err;
}
);
};
在我的组件中,我使用 mapDispatchToProps 和 bindActionCreators 从我的组件中调用此函数,如下所示:
public fetchFunc() {
this.props.fetchPosts("test").then(
res => {
console.log("Res from app", res);
},
err => {
console.log("Err from app", err);
}
);
}
由于我使用的是typescript,所以需要在Props中定义这个函数的类型
interface IProps {
name?: string;
posts: IPost[];
loading: boolean;
fetchPosts: (id: string) => Promise<string | Error>;
}
如果我像上面那样做,Typescript 会抱怨我应该这样做:
fetchPosts: (id: string) => (dispatch: Dispatch<TActions>) => Promise<string | Error>;
如果我这样做,那么当我在组件中使用 then 时,Typescript 会抱怨说该功能不是承诺。
我创建了一个演示,您可以在其中摆弄代码
按“从远程加载”有时会失败,只是为了查看承诺:
【问题讨论】:
-
当你第一次发帖时我看到了这个问题,并敲了我的头一会儿,但无法弄清楚。我相信
bindActionCreators的签名是错误的,因为在运行时,如果你传递一个返回函数的函数,结果是一个函数,该函数将使用dispatch自动调用第二个函数,但打字不反映这个,他们只是返回一个具有相同类型的函数。但是我对 redux 的了解不够,无法肯定地说明这一点 -
为了解决这个问题,我使用了一个类型断言,它既可以编译又具有预期的运行时行为,但感觉很hackish:
bindActionCreators( { fetchPosts: fetchPosts as any as ((id: string) => Promise<string>) }, dispatch );
标签: reactjs typescript redux-thunk