性能优化对React更加重要
shouldComponentUpdate(简称SCU)
基本用法
shouldComponentUpdate(nextProps, nextState){
if(nextState.count !== this.state.count){
return true // 可以渲染
}
return false // 不重复渲染
}
SCU默认返回true
(React 默认: 父组件更新,子组件无条件更新)
- SCU一定要使用吗?
- 需要的时候才优化
- 为什么设置state不能直接修改值
- 否则无法对比优化
- 因此必须配合"不可变值"一起使用
(建议用浅层比较)
PureComponent 和 React.memo
PureComponent, SCU中实现了浅比较 => class组件
memo => 函数组件
(尽量使用浅比较,性能balance)
-------------class组件-------------
class Demo extends React.PureComponent {
...
//内置shouldComponentUpdate(){}
}
-------------函数组件-------------
function demo(){
...
}
export default React.memo(demo)
不可变值 immutable.js
彻底拥抱"不可变值"
基于共享数据额(不是深拷贝),速度快
----- demo -----
const map = Immutable.Map({ a:1, b:2})
const map2 = map.set('b', 50)
map.get('b') // 2
map2.get('b') //50