我是这里描述的“registerEpic”实用程序:在 react-router onEnter 钩子中懒惰地添加新史诗是一种有效的做法吗?
我们的代码需要是等量的,但是在服务器端,第一次触发一个动作,一切都很好。但是第二次触发该动作时,史诗似乎获得了该动作的 2 个副本。这是我的代码:
export const fetchEpic = (action$, store) =>
action$.ofType("FETCH")
.do((action) => console.log('doing fetch', action.payload))
.mergeMap(({meta:{type}, payload:[url, options = {}]}) => {
let defaultHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
options.headers = {...defaultHeaders, ...options.headers};
let request = {
url,
method: 'GET',
responseType: 'json',
...options
};
//AjaxObservables are cancellable... that's why we use them instead of fetch. Promises can't be cancelled.
return AjaxObservable.create(request)
.takeUntil(action$.ofType(`${type}_CANCEL`))
.map(({response: payload}) => ({type, payload}))
.catch(({xhr:{response: payload}}) => (Observable.of({type, payload, error: true})));
}
);
registerEpic(fetchEpic);
因此,我第一次点击触发此操作的页面(服务器端)一切正常,并且我在控制台中获得了一次“正在进行提取”。
但是,刷新页面会产生其中 2 条控制台消息,并且不会触发结果操作。
我在我的史诗注册表中添加了一个“清除”功能,但也许我完全是菜鸟酱,只是没有完全理解它。这是我的中间件:
let epicRegistry = [];
let mw = null;
let epic$ = null;
export const registerEpic = (epic) => {
// don't add an epic that is already registered/running
if (epicRegistry.indexOf(epic) === -1) {
epicRegistry.push(epic);
if (epic$ !== null) { //this prevents the observable from being used before the store is created.
epic$.next(epic);
}
}
};
export const unregisterEpic =(epic) => {
const index = epicRegistry.indexOf(epic);
if(index >= 0) {
epicRegistry.splice(index, 1);
}
}
export const clear = () => {
epic$.complete();
epic$ = new BehaviorSubject(combineEpics(...epicRegistry));
}
export default () => {
if (mw === null) {
epic$ = new BehaviorSubject(combineEpics(...epicRegistry));
const rootEpic = (action$, store) =>
epic$.mergeMap(epic => epic(action$, store));
mw = createEpicMiddleware(rootEpic);
}
return mw;
};