面试题答案
一键面试1. shouldComponentUpdate
shouldComponentUpdate
是 React 类组件的生命周期方法,通过返回 true
或 false
来决定组件是否需要更新。可以在该方法中对比新旧 props
,只有当 props
真正发生变化时才返回 true
进行更新,从而提高性能。
import React, { Component } from 'react';
class ChildComponent extends Component {
shouldComponentUpdate(nextProps) {
// 对比新旧 props 中的 stateValue
return this.props.stateValue!== nextProps.stateValue;
}
render() {
return <div>{this.props.stateValue}</div>;
}
}
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
stateValue: 0
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
stateValue: prevState.stateValue + 1
}));
}
render() {
return (
<div>
<ChildComponent stateValue={this.state.stateValue} />
<button onClick={this.handleClick}>Update stateValue</button>
</div>
);
}
}
export default ParentComponent;
2. PureComponent
PureComponent
是 React 提供的一个基类,它内部自动实现了 shouldComponentUpdate
方法,会对 props
和 state
进行浅比较(shallow comparison)。如果 props
和 state
的引用没有变化,组件不会更新。
import React, { PureComponent } from 'react';
class ChildComponent extends PureComponent {
render() {
return <div>{this.props.stateValue}</div>;
}
}
class ParentComponent extends PureComponent {
constructor(props) {
super(props);
this.state = {
stateValue: 0
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
stateValue: prevState.stateValue + 1
}));
}
render() {
return (
<div>
<ChildComponent stateValue={this.state.stateValue} />
<button onClick={this.handleClick}>Update stateValue</button>
</div>
);
}
}
export default ParentComponent;
3. React.memo
React.memo
是一个高阶组件(HOC),用于函数式组件,和 PureComponent
类似,它会对 props
进行浅比较。如果 props
没有变化,组件不会重新渲染。
import React from'react';
const ChildComponent = React.memo(({ stateValue }) => {
return <div>{stateValue}</div>;
});
const ParentComponent = () => {
const [stateValue, setstateValue] = React.useState(0);
const handleClick = () => {
setstateValue(prevValue => prevValue + 1);
};
return (
<div>
<ChildComponent stateValue={stateValue} />
<button onClick={handleClick}>Update stateValue</button>
</div>
);
};
export default ParentComponent;
总结:
shouldComponentUpdate
适用于类组件,开发者可以自定义对比逻辑,灵活性较高。PureComponent
同样适用于类组件,自动进行浅比较,使用简单,但如果props
或state
中有复杂数据结构可能出现问题。React.memo
用于函数式组件,自动浅比较props
,使用方便,同样在处理复杂数据结构时需注意浅比较的局限性。