redux-saga 根据 UI 组件状态有条件地订阅 worker

redux-saga subscribe workers conditionally depending on UI component state

我有一个全局通用 UI 按钮组件 (<ButtonRefresh />),它存在于基础 UI 组件 <ApplicationBase /> 中。假设我在 ApplicationBase 中有子组件,它们根据路由呈现,例如:HomePageUserDetailPageProductsPageProductDetailPage 等。 这些页面内可以是任意数量的其他组件,例如 UserEntityProductEntityProductEntityList

所有这些组件都应该能够实现自己的数据 retrieve/display 逻辑。

单击刷新按钮时,它会调度一个操作:APP_REFRESH。我有一个 redux-saga 监视这个动作并做一些后台工作(网络调用):

function* appRefreshWatcher() { yield takeEvery(APP_REFRESH, appRefreshWorker); }

我的问题是需要完成的后台工作取决于当前安装的子组件。我不想重新加载数据或更新未显示的实体。

理想情况下,每个组件都能够侦听 APP_REFRESH 操作和 运行 它自己的刷新工作者传奇 - 但只有在挂载时 [=39] =].

我怎样才能 'refreshing' 只处理活动(已安装)的组件?

您可以使用 react-redux-router 将有关当前路线的数据保存在商店中。

然后您可以selectappRefreshWorker中的数据以有条件地刷新数据。

您是否看过 react-boilerplate 存储库采用的方法? https://github.com/react-boilerplate/react-boilerplate

您可以使用 withSaga 方法在组件旁边动态注入(和弹出)sagas。当组件安装或卸载时,sagas 被注入和从存储中弹出。它与 recompose 中的 withReducer 类似。回购示例:https://github.com/react-boilerplate/react-boilerplate/blob/master/app/containers/HomePage/index.js#L132

检查注入实现:https://github.com/react-boilerplate/react-boilerplate/blob/master/app/utils/injectSaga.js#L28。特别是 HOC 上的 componentWillMountcomponentWillUnmount 方法。

我认为您可以使用这种函数式编程方法实现您的目标。