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

后端 未结 6 844
独厮守ぢ
独厮守ぢ 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:56

    In react-redux 7.0.1+ batching is now built-in. Release notes of 7.0.1:

    https://github.com/reduxjs/react-redux/releases/tag/v7.0.1

    Batched Updates

    React has an unstable_batchedUpdates API that it uses to group together multiple updates from the same event loop tick. The React team encouraged us to use this, and we've updated our internal Redux subscription handling to leverage this API. This should also help improve performance, by cutting down on the number of distinct renders caused by a Redux store update.

    function myThunk() {
    
       return (dispatch, getState) => {
    
           // should only result in one combined re-render, not two
    
           batch(() => {
    
               dispatch(increment());
    
               dispatch(increment());
    
           })
    
       }
    
    }
    
    0 讨论(0)
  • 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)
      )
    )
    
    0 讨论(0)
  • 2020-12-31 06:10

    redux-batched-actions Batching action creator and associated higher order reducer for redux that enables batching subscriber notifications for an array of actions.

    0 讨论(0)
  • 2020-12-31 06:13

    By design when the state, which is held by the store, changes the view should render.

    You can avoid this by updating the state once.

    If you are using promises you can use Promise.all to wait for all the promises to resolve and then dispatch a new action to the store with the calculated result. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

    Something like this:

    Promise.all([p1, p2, p3, p4, p5]).then(changes => { 
      dispatch(changes)
    }, err => {
      // deal with error
    });
    

    Of course you'll need an action that will deal with many props, something like addManyProps this should update the state once, resulting in one render.

    0 讨论(0)
  • 2020-12-31 06:15

    @Kokovin Vladislav's answer is correct. To add some additional context:

    Redux will notify all subscribers after every dispatch. To cut down on re-renders, either dispatch fewer times, or use one of several approaches for "batching" dispatches and notifications. For more info, see the Redux FAQ on update events: http://redux.js.org/docs/faq/Performance.html#performance-update-events .

    I also recently wrote a couple of blog posts that relate to this topic. Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability discusses the pros and cons of using thunks, and summarizes several ways to handle batching of dispatches. Practical Redux Part 6: Connected Lists, Forms, and Performance describes several key aspects to be aware of regarding Redux performance.

    Finally, there's several other libraries that can help with batching up store change notifications. See the Store#Store Change Subscriptions section of my Redux addons catalog for a list of relevant addons. In particular, you might be interested in https://github.com/manaflair/redux-batch , which will allow you to dispatch an array of actions with only a single notification event.

    0 讨论(0)
  • 2020-12-31 06:19

    There are ways to achieve the goal:

    Classic way:

    usually: Actions describe the fact that something happened, but don't specify how the application's state changes in response. This is the job of reducers. That also means that actions are not setters.

    Thus, you could describe what has happened and accumulate changes, and dispatch one action something like:

    const multipleAddProp = (changedProps) =>({
       type:'MULTIPLE_ADD_PROP', changedProps
    });
    

    And then react on action in reducer:

    const geo=(state,action)=>{
       ...
       switch (action.type){
       case 'MULTIPLE_ADD_PROP':
         // apply new props
       ...
       }
    }
    

    Another way When rerendering is critical :

    then you can consider to limit components, which could be rerendered on state change. For example you can use shouldComponentUpdate to check whether component should be rendered or not. Also you could use reselect, in order to not rerender connected components after calculating derived data...


    Non standard way: redux-batched-action

    It works something like transaction.

    In this example, the subscribers would be notified once:

    import { batchActions } from 'redux-batched-actions';
    
    const multiGeoChanges=(...arrayOfActions)=> dispatch => {
        dispatch( batchActions(arrayOfActions) );
    }
    
    0 讨论(0)
提交回复
热议问题