如何限制react-redux连接更新重新渲染到特定状态分支? [英] How to limit react-redux connect update re-renders to specific state branches?

查看:59
本文介绍了如何限制react-redux连接更新重新渲染到特定状态分支?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动作和减速器,可以更新全局计数器.快速执行此操作.减速器为每个操作返回状态的新副本.减速器看起来像:

I have an action and reducer that updates a global counter. This action is fired on a rapid interval. The reducer returns a new copy of the state for each action. The reducer looks like:

import { handleActions } from 'redux-actions';
import { sceneTick } from './actions';

export default (state, action) => handleActions({
  [sceneTick]: (state, action) => {
    return {
      ...state,
      loop: action.payload,
    }
  },

我在各种React组件上使用 react-redux connect 方法.并非所有组件都关心此循环计数器.因为我在每个刻度上都在化简器中返回新状态,所以所有使用 connect 订阅的组件都将执行其 mapDispatchToProps ,这将导致不必要的React渲染调用.

I am using react-redux's connect method on various React components. Not all the components care about this loop counter. Because I am returning a new state in the reducer on each tick, all components subscribed with connect get their mapDispatchToProps executed which causes unnecessary React render calls.

其中一个组件如下:

const mapStateToProps = (state, props) => {
  return {
    viewport: state.viewport,
    assets: state.assets,
  };
};


export default connect(mapStateToProps, {})(Component)

即使此组件不依赖于 state.loop ,它也会被触发以重新呈现.这会导致重新渲染,过度渲染,多次渲染,不必要的渲染,性能问题以及不需要重新渲染的组件中的意外行为.

Even though this component has no dependency on state.loop it gets triggered to re-render. This causes re-rendering, over rendering, multiple rendering, unnecessary rendering, performance issues and unexpected behavior in components that need not re-render.

更新我还应该补充一点,在这里我使用 combineReducers ,并且所有的reducer都已应用到完整状态.不确定是否相关.

Update I should also maybe add that I am not using combineReducers here and all reducers are applied to the full state. Not sure if relevant.

推荐答案

Redux connect 接受 areStatesEqual 函数选项,该选项可用于将相等性检查缩小到特定状态分支机构.

Redux connect accepts a areStatesEqual function option that can be used to narrow down equality checks to specific state branches.

export default connect(
  {},
  {},
  null,
  {
    areStatesEqual: (next, prev) => {
      return (
        prev.branch === next.branch
      );
    }
  }
)(Component);

这篇关于如何限制react-redux连接更新重新渲染到特定状态分支?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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