Reactjs 即使组件的属性或状态没有更改,也会调用React-shouldComponentUpdate()
我向React组件添加了生命周期方法Reactjs 即使组件的属性或状态没有更改,也会调用React-shouldComponentUpdate(),reactjs,Reactjs,我向React组件添加了生命周期方法 shouldComponentUpdate(nextProps, nextState) { console.log(nextProps, nextState); console.log(this.props, this.state); return false; }, 我的问题是,即使nextProps和nextState与当前的props和state完全相同,也会对组件调用此方法。当我比较nextrops和this.
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps, nextState);
console.log(this.props, this.state);
return false;
},
我的问题是,即使nextProps和nextState与当前的props和state完全相同,也会对组件调用此方法。当我比较nextrops和this.props的console.log语句时,它们是完全相同的。国家也是如此
那么为什么应该调用ComponentUpdate呢
每当我更改父组件的状态时,就会调用它。但实际组件上的道具或状态都没有改变。那为什么叫它
仅供参考,我正在使用React with Meteor
进一步澄清:
我想知道为什么要首先调用函数
shouldComponentUpdate
。该组件的状态或支柱均未更改。但是父组件的状态正在更改。React自动调用shouldComponentUpdate
,它在重新呈现过程开始之前触发(在父组件的情况下)。因此,它自然会被频繁调用
此函数的默认实现返回true,因此要停止重新渲染,需要在此处返回false:
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps, nextState);
console.log(this.props, this.state);
return false;
}
因此,总之,React通过允许用户使用shouldComponentUpdate缩短进程,避免执行协调DOM子树所需的昂贵DOM操作
shouldComponentUpdate
的目的是指示是否应调用render
。在您的情况下,某个父组件已渲染,并表示它还希望渲染子组件的实例
shouldComponentUpdate
是您缩短渲染时间并说“不要麻烦,这里没有任何更改”的机会
现在,对于你的问题,“既然没有改变,为什么还要叫它?”?React不会比较新旧道具本身。您可以获得一个mixin来为您执行此操作(即,PureRenderMixin
),但默认情况下,React只允许渲染运行
React不做比较的原因有两个。首先,与分析道具和状态相比,跳过渲染的性能节省可能微不足道。由于React的渲染机制已经过优化,以避免不必要的DOM操作,因此它可以假定组件需要更新并期望合理的性能。其次,进行比较并不完全是直截了当的。您的道具是原语、不可变、数组、复杂对象吗?是否需要进行深入比较
React的模型是“默认情况下,我们将呈现所有要求的内容。如果您希望某些内容不符合性能要求,请继续并通过实现
shouldComponentUpdate
”告诉我们。shouldComponentUpdate()
每次都被调用:
- 每次重新渲染父组件时,都会更新道具。这包括使用完全相同的道具值进行重新渲染的所有场景
- 通过调用
(react允许的唯一方法)更新状态。这包括状态值完全相同的所有场景setState()
- 制作没有
的第一个版本,并确保相同的道具集和状态导致呈现相同的结果shouldComponentUpdate()
- 添加并调试
shouldComponentUpdate()
shouldComponentUpdate() – Returns true or false value based on certain conditions.
If you want your component to update, return true else return false.
By default, it returns
正确。
if(shouldComponentUpdate) {
// then render() is called and update UI/view
}else{
// then render() is not called ....[Don't update UI]
}
shouldComponentUpdate方法返回布尔值 指定React是否应继续渲染 默认值为true 何时使用shouldComponentUpdate:
当您希望组件在上一个状态值等于下一个状态值时不渲染时会调用它,因为您返回的是true,如果返回的是false,则不会调用。我的问题是,为什么要首先调用该函数。道具或状态没有改变。但我发现调用它是因为父组件正在重新呈现,因此称为shouldComponentUpdate。我想…这只是一个简短的评论,请看下面我的完整答案。。。