Redux 等待调度并处理错误



我在打字稿中使用这样的redux-thunk:

//store
export const thunkCreateArticle = (articleCreateView: ArticleCreateView):
ThunkAction<void, ArticleState, BlogClient, Action<string>> => async (dispatch, _, api) => {
const article = await api.createArticle(articleCreateView);
dispatch({
payload: article,
type: CREATE_ARTICLE,
});
};
//component
const mapDispatchToProps = (dispatch: ThunkDispatch<{}, {}, any>): DispatchProps => {
return {
addArticle: async (add: v.ArticleCreateView) => {
dispatch(thunkCreateArticle(add));
}
}
}

我想在mapDispatchToPropsaddArticle等待dispatch,这样我就可以在addArticle完成后做一些事情并使用 try-catch 处理错误。我为此找到的所有解决方案都使用全局错误处理程序,这很糟糕的 IMO。我的客户端是有状态的,所以我使用 thunk 中的额外参数来"注入"它。

我通过分配正确的类型来解决它:

export type ActionTypes = ....;
export type BlogThunkResult<R> = ThunkAction<R, RootState, BlogClient, ActionTypes>;
export type BlogThunkDispatch = ThunkDispatch<RootState, BlogClient, ActionTypes>;

export const thunkUpdateArticle = (articleId: number, articleUpdateView: ArticleCreateView):
BlogThunkResult<Promise<void>> => async (dispatch, _, api) => {
const article = await api.updateArticle(articleId, articleUpdateView);
dispatch({
payload: article,
type: UPDATE_ARTICLE,
});
};

如果我现在使用dispatch我会得到一个可以等待的承诺,并且错误会正确传递给调用方。

最新更新