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

查看:216
本文介绍了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")));

但是这会导致每次派遣后的渲染反应。我是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.

推荐答案

有很多方法可以达到目标:

There are ways to achieve the goal:

经典方式:

通常:
操作描述 事实发生了什么 ,但不要指定应用程序的状态如何响应变化。这是减速机的工作。
这也意味着操作不是设置者

因此,您可以描述已发生的事情并累积更改并发送一个 行动
类似于:

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中的操作作出反应:

And then react on action in reducer:

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






另一种方式重新渲染至关重要:

然后你可以考虑限制组件,可以在状态变化时重新渲染。
例如,您可以使用 shouldComponentUpdate 来检查是否应该呈现组件

另外你可以使用重新选择,以便在计算派生数据后不再重新连接已连接的组件
...

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

它类似于交易。

在此例如,订阅者将收到一次通知:

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天全站免登陆