我有这个非常简单的组件,它连接到redux状态并返回{fruit,vegetables}.一切正常,但是假设我在Component中有一个图表,如果只从API接收更新的蔬菜,则每次都会重新创建图表. 这是我的组件: co
这是我的组件:
const Products = ({ fruit, vegetable }) =>
<div className='Products'>
<div>{vegetable.map(....logic here)}</div>
<div>{Math.random()}</div> // this is to illustrate the component is rendering every time
<Graph>Here will be a chart or a graph with fruit</Graph> //but it gets re-rendered even though there is no new fruit
</div>
const mapStateToProps = (state) => {
return {
fruit: state.data.fruit,
vegetable: state.data.vegetable,
}
}
export default connect(mapStateToProps)(Products)
在我看来,无论哪个状态更新,它都会重新呈现整个组件.
有办法防止这种情况吗?
当React组件被渲染时,它下面的整个组件树也会被渲染 – 除了shouldComponentUpdate hook返回false的组件.因此,在您的情况下,如果Products组件被渲染,那么Graph组件也是如此.你有两个选择:
>如果您的Products组件不使用Graph组件之外的fruit prop,您可以直接将Graph组件连接到fruitstate,并使用connect函数的pure选项来避免在水果没有更改时重新渲染
>您可以在Graph组件中定义shouldComponentUpdate挂钩以手动跳过不必要的渲染,或者使用帮助程序库为您执行此操作,例如重构库的纯辅助程序
第一个选项是优化react / redux应用程序/避免不必要的渲染通常开始:将组件连接到存储在最低级别的有意义的位置.第二个选择更多的是逃生舱 – 但仍然常常有用.
正如您所提到的,您使用无状态组件,您可以使用更高阶的组件从shouldComponentUpdate挂钩中受益.要了解它是如何工作的,这里的简单实现如下所示:
function pure(BaseComponent, shouldUpdateFn) {
return class extends Component {
shouldComponentUpdate(nextProps) {
return shouldUpdateFn(this.props, nextProps);
}
render() {
return <BaseComponent { ...this.props } />;
}
}
}
这将为您提供一个纯HOC,您可以在应用程序上重复使用它以避免不必要的渲染:它通过将无状态组件包装到具有所需钩子的新组件中来工作.你可以像这样使用它,例如:
export default pure(Graph, (props, nextProps) => props.fruit !== nextProps.fruit)
尽管如此,我强烈建议您重新考虑重构,其中包含更精细的实现,并避免重新发明轮子.
