一、React.PureComponent簡介
React.PureComponent是一種優化React應用性能的方式,它可以進行淺比較(shallow compare)從而減少不必要的渲染。React.PureComponent繼承自React.Component,並實現了shouldComponentUpdate方法,會在渲染之前進行props和state的淺比較,如果沒有改變則不進行渲染。因為React.PureComponent只會在props或state改變時才會重新渲染,所以它可以實現對React應用的優化。
二、React.PureComponent與React.Component的區別
React.PureComponent與React.Component的最大區別就在shouldComponentUpdate方法的實現上。如果需要使用React.Component實現shouldComponentUpdate的時候,需要手動比較props和state的改變情況,而React.PureComponent則會自動實現這一過程,大大減少了手動實現shouldComponentUpdate所帶來的工作量。
但需要注意的是,因為React.PureComponent實現shouldComponentUpdate方法的方式是淺比較,所以如果在應用中使用了複雜的props和state對象,比如數組和對象,可能會出現誤判的情況,導致組件不渲染或者誤渲染,因此在使用React.PureComponent時需要格外注意。
三、使用React.PureComponent的注意事項
1、使用React.PureComponent時需要注意props和state的改變方式。因為React.PureComponent只會在props和state的值發生改變時才會進行渲染,所以應當儘可能地避免直接修改props和state,而是使用不可變的方式生成新的props和state。
示例:
class Example extends React.PureComponent {
constructor(props) {
super(props);this.state = {
data: [
{ id: 1, name: 'Tom' },
{ id: 2, name: 'Jerry' },
{ id: 3, name: 'Spike' }
]
};
}handleClick = () => {
// 錯誤示例:直接修改state
this.state.data[0].name = 'Tim';// 正確示例:使用不可變的方式生成新的state
const newData = [...this.state.data];
newData[0].name = 'Tim';
this.setState({ data: newData });
}render() {
return (
-
{this.state.data.map(item => (
- {item.name}
))}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/293040.html