我在這裏所描述的「registerEpic的效用:Is it an efficient practice to add new epics lazily inside react-router onEnter hooks?終極版,可觀察到的多個動作
我們的代碼需要isomoprhic,但在服務器端,一個動作被觸發的第一時間,一切都好。但是,第二次觸發行動時,史詩似乎會得到該行動的兩個副本。這裏是我的代碼:
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;
};
@Ben是否回答了你的問題? – jayphelps