来源:未知 时间:2024-05-11 23:00 作者:小飞侠 阅读:次
[导读] shouldComponentUpdate 纯组件只能进行浅层比较,要进行深层比较,使用 shouldComponentUpdate, 它用于编写自定义比较逻辑。 返回true重新渲染组件,返回false阻止重新渲染 函数第一个参数为 ne...
|
shouldComponentUpdate 纯组件只能进行浅层比较,要进行深层比较,使用 shouldComponentUpdate, 它用于编写自定义比较逻辑。 返回true重新渲染组件,返回false阻止重新渲染 函数第一个参数为 nexProps, 第二个参数为 nexState 第三个参数为 nextContext。 注意: 如果返回false `componentWillUpdate` *并且不会调用“componentDidUpdate”。 下面代码演示,定时1秒后根据判断是否渲染组件 import React, { Component, PureComponent } from 'react'
class App extends Component {
constructor() {
super()
this.state = {
person: {
name: '张三',
age: 20 ,
job: 'waiter'
}
}
}
updateName() {
setTimeout(() => {
this.setState({
person: {
...this.state.person,
job: 'chef'
}
})
}, 1000)
}
// 当组件挂载后
componentDidMount() {
this.updateName()
}
// 深度重新渲染
shouldComponentUpdate(nextProps, nextState) {
// ...重点
// 这里根据自己需求判断是否重新渲染组件
if(
nextState.person.name === this.state.person.name
&& nextState.person.job === this.state.person.job
) {
return false
}
console.log('shouldComponentUpdate', nextProps, nextState)
return true
}
render(state) {
return <div>
App
<br/>
{this.state.person.name} <br/>
{this.state.person.age} <br/>
{this.state.person.job}
</div>
}
}
export default App;以上就是react性能优化之shouldComponentUpdate全部内容,感谢大家支持自学php网。 |
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com