繁体   English   中英

redux-saga 中的批处理操作

[英]Batching actions in redux-saga

我在https://react-redux.js.org/api/batch上读到可以使用batch以确保在 React 之外调度的多个操作只会导致单个渲染更新”,就像这样(我在 React 中使用事件处理程序即):

...
const submitData = event => {
    // ... some code before
    batch(() => {
        dispatch(first())
        dispatch(second())
    })
}
...

但我的问题是如何在redux-saga中正确地batch操作,以便结果是一次重新渲染而不是多次重新渲染,同时从传奇中分派多个操作? 我尝试将多个put all数组中,但不确定它是否真的批量put

yield all([
    put(addFirst({first: 1})),
    put(addAnother({second: 2)),
]);

上述方法是因为我已经阅读了https://github.com/manaflair/redux-batch上的文档,作者在其中写道“自从编写了这个包后,redux-saga 得到了改进并使用了 all([ put(...), put(...) ]) 似乎将两个操作正确地批处理到一个订阅事件中,使 redux-batch 在这种情况下变得多余。 ”,https://github.com/manaflair/redux-batch/issues/ 21另一个人写道,批处理由React unstable_batchedUpdates API处理。 仍然redux-toolkit (我使用的)有一个redux-batch作为store enhancer的例子( https://github.com/reduxjs/redux-toolkit/blob/master/docs/api/configureStore.md )。

因此,如果有人知道正确的方法,请分享您的知识! 最好的祝福

编辑:我只在 React 事件处理程序中使用batch来批处理多个操作。 redux-saga我想使用redux-batch包。

所以正确的方法(如果使用 redux-batch 显然 redux-toolkit 似乎喜欢因为示例)是:

import { reduxBatch }                            from '@manaflair/redux-batch';
import { put, takeEvery }                        from 'redux-saga/effects';
import createSagaMiddleware                      from 'redux-saga';
import { applyMiddleware, compose, createStore } from 'redux';

let sagaMiddleware = createSagaMiddleware();
let store = createStore(reducer, compose(reduxBatch, applyMiddleware(sagaMiddleware), reduxBatch));

sagaMiddleware.run(function* () {
  yield takeEvery(`*`, function* (action) {

    // Duplicate any event dispatched, and once again, store
    // listeners will only be fired after both actions have
    // been resolved/

    yield put([ action, action ]);

  });
});

因此yield put([ action, action ]); ,有一个数组放入并分派多个动作?

我是 Redux 维护者和 Redux Toolkit 的作者。

实际上,我刚刚写了一篇题为A Comparison of Redux Batching Techniques的博文,其中涵盖了 Redux 操作可用的各种形式的批处理。

正如我刚刚在那个redux-batch问题中评论的那样:

React-Redux 本身内的unstable_batchedUpdates()用法仅尝试最小化单个分派中的嵌套重新渲染。 这与该项目的目标不重叠,该项目试图允许一次分派多个操作,同时仅一次通知商店订阅者。

根据您最初的问题,我不确定您是否可以在 sagas 中正确使用 React-Redux 的batch() API,因为需要yield put() batch() API(它只是 React 自己的unstable_batchedUpdates() API,重新导出)依赖于跟踪在单个事件循环滴答期间排队的任何 React 状态更新,我怀疑使用生成器可能无法处理它。 我必须看到实际的例子才能确定。

无论如何,根据博客文章,批处理有多种选择,它们以不同的方式工作。 这完全是您要解决的实际用例的问题。

根据文档,我认为您可以通过 thunk 来put这一点

yield put((dispatch) => {
  batch(() => {
    dispatch(action1);
    dispatch(action2);
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM