1、PureComponent 只是 state - nextState 和 props - nextProps 的浅比较
基础类型::String,Number,Boolean,Null,undefined,symbol(ES6)
引用类型:Object、Array、RegExp、Date、Function
浅比较:比较基础类型的值,比较引用类型的引用地址
举个例子:
const a = 100
const b = 100
const obj = { a: 1 }
const obj1 = obj
console.log('基础类型比较:', a === 100) // true
console.log('基础类型比较:', a === b) // true
console.log('引用类型比较:' , obj === { a: 1 }) // false
console.log('引用类型比较:', obj === obj1) // true
工作机制:如果比较后,props 和 state 浅比较之后无变化,组件不更新,以此减少渲染次数来优化组件性能
PureComponent会影响自身,也会影响子组件,建议仅当展示组件,不建议把父组件设置成 PureComponent
因为purecomponent只进行浅比较,所以使用该方法时,适当使用拓展运算符[...], {...}
2、shouldComponentUpdate 有两个参数 (nextProps, nextState),可以提前捕捉下一阶段的 props 和 state
上面说到 PureComponent 只是浅比较,shouldComponentUpdate 可以用于处理 PureComponent 无法处理的引用类型比较。
举个例子:
/...
state = {
arr: [1]
}
// 假设 this.props = { user: { age: 24 } }
shouldComponentUpdate(nextProps, nextState) {
if (this.props.age === nextProps.age) { // 对象的值,也可以对整个对象进行比较,此处就不拓展了
return false // 不更新
}
if (this.state.arr.join() === nextState.arr.join()) { // 数字比较,此处使用 join 方法,也可以用更多方法
return false
}
return true
}
.../
工作机制:如果返回 true,组件更新渲染,否则不渲染
网友评论