gpt4 book ai didi

reactjs - redux-saga 无法捕获存储增强器调度的操作

转载 作者:行者123 更新时间:2023-12-03 13:54:47 28 4
gpt4 key购买 nike

我需要在我的 redux 应用程序中使用存储增强器(reactReduxFirebase 来自 react-redux-firebase )。这个增强器调度一个 Action ,它看起来或多或少像这样(非常简化):

const reactReduxFirebase = (next) => {
return (reducer, initialState, middleware) => {
const store = next(reducer, initialState, middleware);
store.dispatch({
type: 'DUMMY_ACTION'
});
return store;
}
}

// usage
const sagaMiddleware = createSagaMiddleware();
const middleware = [sagaMiddleware];
const store = createStore(
reducer,
initialState,
compose(
applyMiddleware(...middleware),
reactReduxFirebase
)
);
sagaMiddleware.run(sagas);

// sagas.js
function* handle(action) {
console.log(action);
}

function* saga() {
yield takeEvery('*', handle);
}

export default saga;

我希望 saga 监听所有操作并 console.log 它们,但它无法捕获增强器分派(dispatch)的“DUMMY_ACTION”,因为它是在 saga 开始监听之前分派(dispatch)的 (sagaMiddleware.run(sagas); )。从 redux-saga 文档看来 saga 必须在 applyMiddleware 之后运行,所以我不能让 saga 在增强器之前运行。有没有办法让它发挥作用,让传奇也能捕捉到增强器的 Action ?

最佳答案

基于applyMiddlware的解决方案:

import createSagaMiddleware from 'redux-saga';
import { takeEvery } from 'redux-saga/effects';
import { createStore, compose } from 'redux';
import {
reducer
} from '../reducers';

function sagaPreinitMiddleware(saga) {
return (createStore) => (reducer, preloadedState, enhancer) => {
const sagaMiddleware = createSagaMiddleware();

const store = createStore(reducer, preloadedState, enhancer);
let dispatch = store.dispatch;
const middlewareAPI = {
getState: store.getState,
dispatch: (action) => dispatch(action)
};
dispatch = compose(sagaMiddleware(middlewareAPI))(store.dispatch);
sagaMiddleware.run(saga); // run the saga
return {
...store,
dispatch
};
};
}

const reactReduxFirebase = (next) => {
return (reducer, initialState, middleware) => {
const store = next(reducer, initialState, middleware);
store.dispatch({
type: 'DUMMY_ACTION'
});
setTimeout(store.dispatch({
type: 'DUMMY_ACTION_1'
}), 100);
return store;
};
};

// usage
const middleware = [];
const store = createStore(
reducer,
0,
compose(
reactReduxFirebase,
sagaPreinitMiddleware(sagas)
)
);


// sagas.js
function* handle(action) {
console.log(action);
}

function* sagas() {
yield takeEvery('*', handle);
}

日志:

   00000000: [reducer] action Object {type: "@@redux/INIT"}
00000008: [reducer] action Object {type: "DUMMY_ACTION"}
Object {type: "DUMMY_ACTION"}
00000011: [reducer] action Object {type: "DUMMY_ACTION_1"}
Object {type: "DUMMY_ACTION_1"}

关于reactjs - redux-saga 无法捕获存储增强器调度的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41406362/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com