【问题标题】:React Boilerplate: Dumb components re-render when the data inReact Boilerplate:当数据进入时,哑组件重新渲染
【发布时间】:2018-07-19 18:54:19
【问题描述】:

我有一个用过的 react-boilerplate 来为我的项目设置基础。考虑我有一个容器和 2 个组件(哑组件),如下所示,

App
  - HomePage(Connected component with sidebarData and detailedData)
     - SideBar(data=sidebarData)
     - DetailedView(data=detailedData)
State
  {
    "sidebarData": makeSelectorSideBarData(), // reselect selector
    "detailedData": makeSelectorDetailedViewData(), // reselect selector
  }

很明显,子组件依赖于单独的数据。但是当我的detailedData 发生变化时,它也会重新渲染SideBar 组件。

有没有办法通过使用 redux/reselect 并且不实现 shouldComponentUpdate() 来避免这种情况?

【问题讨论】:

标签: reactjs redux reselect react-boilerplate


【解决方案1】:

如果您不希望组件在给定的道具更改之前重新渲染,您可以使用PureComponent。只要确保你知道浅的 prop 和 state 比较就足以满足你的用例:

PureComponentshouldComponentUpdate() 只是浅比较 对象。如果这些包含复杂的数据结构,它可能会产生 更深层次差异的假阴性

【讨论】:

【解决方案2】:

您可以使用 PureComponent 替代方案 - shouldComponentUpdate-Children - https://github.com/NoamELB/shouldComponentUpdate-Children

import {shallowEqual} from 'shouldcomponentupdate-children';

class MyComponent extends React.Component {
    shouldComponentUpdate(nextProps, nextState) {
        return shallowEqual(this.props, nextProps, this.state, nextState);
    }
}
export default MyComponent;

github 链接还包括一个实时的 codepen 示例。

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 2016-08-28
    • 2021-06-19
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多