React + Redux,如何不是在每次调度之后而是在几次之后渲染? [英] React + Redux, How to render not after each dispatch, but after several?

查看:19
本文介绍了React + Redux,如何不是在每次调度之后而是在几次之后渲染?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对商店进行多项更改,但在完成所有更改之前不会呈现.我想用 redux-thunk 做到这一点.

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.

这是我的动作创建者:

function addProp(name, value) {
    return { type:'ADD_PROP', name, value }
}

function multiGeoChanges(...changes) {
    // my goal here is to make multiple changes to geo, and make sure that react doesnt update the render till the end
    return async function(dispatch, getState) {
        for (let change of changes) {
            dispatch(change);
            await promiseTimeout(2000);
        }
    }
}

我像这样派遣我的异步动作创建者:

I dispatch my async action creator like this:

store.dispatch(multiGeoChanges(addProp(1, "val1"), addProp(2, "val2"), addProp(3, "val3")));

然而,这会导致在每次 dispatch 后进行渲染.我是 redux-thunk 的新手,我从未使用过异步中间件,但我认为它可以帮助我.

However this is causing react to render after each dispatch. I am new to redux-thunk, I never used async middleware, but I thought it could help me here.

推荐答案

实现目标的方法有:

经典方式:

通常:操作描述了某事发生的事实,但不指定应用程序的状态如何响应变化.这是减速机的工作.这也意味着行动不是制定者.

因此,您可以描述发生的事情并积累变化,然后发送一个动作类似:

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

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

然后对reducer中的action做出反应:

And then react on action in reducer:

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

<小时>

另一种方式当重新渲染很重要时:

然后您可以考虑限制组件,这些组件可以在状态更改时重新呈现.例如,您可以使用 shouldComponentUpdate 来检查组件是否应该渲染与否.你也可以使用 reselect,为了不重新渲染连接的组件计算得出的数据后...

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...

非标准方式: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) );
}

这篇关于React + Redux,如何不是在每次调度之后而是在几次之后渲染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆