我尝试在史诗中使用history
React钩子,这是个好主意吗?在下面的代码中,我尝试在史诗中使用history
,并且我觉得以某种方式做得不好,有人可以解释一下在史诗中编写React挂钩是否是个好主意吗?如果没有,为什么不呢?
const saveEstimateEpic: Epic<AppActions, AppActions, AppStore, EstimateEpicsDependencies> =
(
action$,
store$, // store$
{ estimates },
) =>
action$.pipe(
// select our request action only
filterAction(saveEstimateDraft.request),
// map each request action to new stream and merge these streams
flatMap(action => {
const loadedEstimate = selectLoadedEstimate(store$.value);
const draftEstimate = selectDraftEstimate(store$.value);
const result$ = loadedEstimate
? estimates.patchEstimate(
loadedEstimate.id,
draftEstimate as EstimatePatchData,
action.payload ? 'completed' : null,
)
: estimates.createEstimate(
draftEstimate as EstimateCreationData,
action.payload ? 'completed' : null,
);
// call asyncProcess() and delay until promise is fulfilled
return result$.pipe(
takeUntil(action$.pipe(filterAction(saveEstimateDraft.request))),
// map promise result to success action
flatMap(result => {
const isCatalogChanged =
selectActualRegion(store$.value) !== result.region ||
selectActualCatalogId(store$.value) !== result.catalog_id;
const successAction = saveEstimateDraft.success(result);
const fetchCatalogAction = fetchCatalog.request({
catalogVersion: result.catalog_id.toString(),
catalogRegion: result.region,
});
const history = useHistory();
tap(() => history.push('/estimates'));
return isCatalogChanged ? [successAction, fetchCatalogAction] : [successAction];
}),
// catch error if any and emit failure action
catchError((error: Error) => {
const userError = errorHandler(error, { allowRuntypesValidation: false });
return of(
saveEstimateDraft.failure(userError),
setNotificationAction({
type: 'error',
title: 'Cannot save the estimate',
payload: userError,
}),
);
}),
);
}),
);