我在我的React应用程序中使用 PureComponent
以获得更好的性能,它有 props
但我不希望它在 props
更改时运行render方法 . 我知道我们不能在 React.PureComponent
中使用 shouldComponentUpdate
,但我的问题是:
有没有办法避免更新 React.PureComponent
?
我希望这个组件根本不更新/渲染 .
编辑:我在pureComponent中使用 shouldComponentUpdate
时收到此警告:
警告:GameObjectFall有一个名为shouldComponentUpdate()的方法 . 扩展React.PureComponent时不应使用shouldComponentUpdate . 如果使用了shouldComponentUpdate,请扩展React.Component .
3 回答
PureComponent
更改生命周期方法shouldComponentUpdate并添加一些逻辑以自动检查组件是否需要重新渲染 . 这允许PureComponent仅在检测到状态或道具的更改时才调用方法呈现,因此,可以在不必编写额外检查的情况下更改许多组件中的状态 .但是,您还可以使用经过验证的方法
shouldComponentUpdate
手动确定重新渲染的必要性 . 它不会覆盖PureComponent逻辑,但会添加您在shouldComponentUpdate
的自定义实现中添加的任何其他内容请参阅说明此内容的片段
根据PureComponent Documentation,它只在
shouldComponentUpdate()
进行浅层比较 . 因此,如果所有道具都包裹在一个对象中,并且如果改变该对象中的属性,则组件将不会重新渲染,因为浅层比较将始终为true .假设为
propContainer = {name: "John", age: "20"}
和this.props.container = propContainer
,则 propContainer 对象内的变异(更改名称,年龄值)将不会重新呈现该组件 .当使用
PureComponent
时,方法shouldComponentUpdate
有一个实现,它只进行浅层比较 . 当你的道具是布尔,字符串或任何其他原始类型时,你应该使用它 .您可以将实现实现为
shouldComponentUpdate
,这将覆盖默认的浅层比较 .当我说浅层比较时,我的意思是如果你在对象/数组之间进行比较,你会得到错误的比较 . 例如: