React + Redux, How to render not after each dispatch, but after several?

后端 未结 6 870
独厮守ぢ
独厮守ぢ 2020-12-31 05:28

I am trying to make multiple changes to the store, but not render till all changes are done. I wanted to do this with redux-thunk.

Here is my action creator:

6条回答
  •  旧巷少年郎
    2020-12-31 05:59

    Coming to this a bit late, but I think this is a much nicer solution, which enables you to add meta.batch to actions you would like to batch together into a single react update. As a bonus this approach works with asynchronous actions.

    import raf from 'raf'
    import { batchedSubscribe } from 'redux-batched-subscribe'
    
    let notify = null
    let rafId = null
    
    const shouldBatch = action => action?.meta?.batch
    
    export const batchedSubscribeEnhancer = batchedSubscribe(freshNotify => (notify = freshNotify))
    
    export const batchedSubscribeMiddleware = () => next => action => {
      const resolved = next(action)
    
      if (notify && rafId === null && !shouldBatch(action)) {
        notify()
      } else if (!rafId) {
        rafId = raf(() => {
          rafId = null
          notify()
        })
      }
    
      return resolved
    }
    

    Then connect up to your store

    mport { applyMiddleware, compose, createStore } from 'redux'
    import { batchedSubscribeMiddleware, batchedSubscribeEnhancer } from './batching'
    
    const store = createStore(
      reducer,
      intialState,
      compose(
        batchedSubscribeEnhancer,
        applyMiddleware(batchedSubscribeMiddleware)
      )
    )
    

提交回复
热议问题