【问题标题】:Events handled by another saga (Redux-Saga)由另一个 saga (Redux-Saga) 处理的事件
【发布时间】:2021-12-03 23:44:36
【问题描述】:

我正在尝试为我的所有 sagas 创建一个错误拦截器,在分析了 redux-saga eventChannel 之后,我尝试创建一个这样的 saga:

export function interceptor() {
  return eventChannel(() => {
    api.interceptors.response.use(
      (response) => response,

      (error) => {
        const { response } = error;

        if ([401, 403].includes(response.status)) {
            emit(AuthCreators.logoutRequest());
        }

        return Promise.reject(error);
      }
    );

    return () => null;
  });
}

在 rootSaga 中是这样调用的:

export default function* rootSaga() {
    return yield all([fork(interceptor), anotherSaga, anotherSaga2]);
}

这样,每次我的其他 sagas 有一个 catch 时,拦截器就会被触发,但是我应该触发其他 saga 中的 logoutRequest 的发出不会被触发。

  • emit 如何调用其他 saga?
  • 这是创建错误拦截器的最佳方式吗?

感激不尽

【问题讨论】:

    标签: javascript reactjs react-redux redux-saga


    【解决方案1】:

    也许我不完全理解你的问题,但这可能会对你有所帮助

    const saga = [
    anotherSaga, anotherSaga2
    ]
    
    yield all(sagas.map((saga) => spawn(function* () {
            try {
                yield call(saga);
            } catch (e) {
                // console.log(e);
                // here we should store all errors in some service...
            }
        })));
    

    【讨论】:

    • 我想创建一个函数,任何 saga 中发生的任何错误都会触发它,这样我就可以处理一些标准错误,而不必在每次 TRY/CATCH 中重复
    • 好吧,试试上面的 sn-p,应该可以为你工作
    猜你喜欢
    • 2018-12-13
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 2019-06-14
    • 2020-05-08
    • 1970-01-01
    • 2019-03-03
    • 2017-11-13
    相关资源
    最近更新 更多