Component和PureComponent
首先來說一下 Component
和 PureComponent
的區別,其實他們倆基本是一樣的,因為后者繼承前者,細微的區別就是 PureComponent
可能會幫我們提升程序的性能,怎么說呢?它的內部實現了 shouldComponentUpdate
方法,我們應該都知道這個方法是干嘛的吧,幫助我們減少不必要的 render
,我們通常會在 shouldComponentUpdate
方法中判斷props或者state的值是不是和之前的一樣,然后來決定是否重新 render
,來看一個最簡單的例子:
class Test extends PureComponent<any, any> {
constructor(props: any) {
super(props)
this.state = {
isShow: false,
}
}
click = () => {
this.setState({
isShow: true
})
}
render() {
console.log('render');
return (
<div>
<button onClick={this.click}>index</button>
<p>{this.state.isShow.toString()}</p>
</div>
)
}
}
在上面這個例子中,通過按鈕去改變state中isShow這個屬性的值,但是第一次改變之后后面這個值就不會變了,如果用PureComponent的話那么只會在第一次點擊的時候會重新render,但是使用Component的話,那么每次點擊都會觸發render。所以這里使用PureComponent能幫我們提升一定的性能。那么有些人可能就會說那我是不是只用PureComponent就好了,那我只能說
我們把上面的isShow參數換一下,換成一個對象試試:
constructor(props: any) {
super(props)
this.state = {
user: {
name: '24K純帥',
gender: '男'
}
}
console.log('constructor');
}
click = () => {
this.setState((preState: any) => {
const { user } = preState
user.name = "Jack"
return { user }
}, () => {
console.log(this.state.user)
})
}
render() {
console.log('render');
return (
<div>
<Button primary="true" onClick={this.click}>index</Button>
<Button>{this.state.user.name}</Button>
</div>
)
}
}
我們發現如果使用PureComponent的話,點擊按鈕之后都不會觸發render了,使用Component才行,看到這里是不是腦袋一大堆問號
原來PureComponent內部實現的shouldComponentUpdate方法只是進行了淺比較,怎么說呢,你可以理解為只是針對基本數據類型才有用,對于對象這種引用數據類型是不行的。
React.memo()
其實這個和PureComponent功能是一樣的,只不過memo是提供給函數組件使用的,而PureComponent是提供給class組件使用的,還有一點就是memo提供一個參數可以讓我們自行配置可以對引用數據做比較然后觸發render