【发布时间】:2020-05-08 00:45:35
【问题描述】:
我在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 冗余。",但是在@987654323 @另一个人写道,批处理由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 ]);,在 put 中有一个数组并 dispatch 多个 action?
【问题讨论】:
标签: reactjs redux redux-saga batching