[英]Listen for dispatched action in Redux
我想知道是否有办法监听在redux中成功调度的操作?
在Angular的ngxs状态管理库中,我可以执行以下操作:
ngOnInit() {
this.actions$
.pipe(
ofActionSuccessful(AddedThingToDo),
map((event: AddedThingToDo) => event.thingToDo),
tap(thingToDo => console.log('Action was successfully dispatched'))
)
.subscribe();
}
当我知道AddedThingToDo
已成功调度时,可以在其中执行操作。 这可能类似于关闭模态,或者调度另一个动作。
我在Angular 1.x中使用ng-redux
,但是我认为原理应与对React Redux的使用相同。
我一直在解决它的唯一方法是在我的操作中使用回调,但是感觉很不对劲:
export const addThingToDo = (model: IThingToDo, onSuccess?: (model: IThingToDo) => void) =>
async (dispatch: Dispatch) => {
dispatch(addingThingToDo());
try {
const createdItem = await api.post<IThingToDo>(url, model);
dispatch(addedThingToDo(createdItem));
if (onSuccess) {
onSuccess(createdItem);
}
}
catch (ex) {
dispatch(addThingToDoFailure(ex));
}
};
原来, redux-thunk
支持返回promise,所以我可以只返回promise,而不必使用回调方法。
export const addThingToDo = (model: IThingToDo) =>
async (dispatch: Dispatch): Promise<IThingToDo> =>
await new Promise<IThingToDo>(async (resolve, reject) => {
dispatch(addingThingToDo());
try {
const newItem = await api.post<IThingToDo>(url, model);
dispatch(addedThingToDo(newItem));
resolve(newItem);
} catch (ex) {
dispatch(addThingToDoFailure(ex));
reject(ex);
}
});
this.addThingToDo(thingToDo)
.then(t => navigateTo(`/things-to-do/${t.id}`));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.