面试题答案
一键面试1. 使用 shouldComponentUpdate
- 实现思路:
shouldComponentUpdate
是 React 组件的生命周期方法,它接收nextProps
和nextState
作为参数。- 在这个方法中,我们可以对比当前的
props
和state
与即将更新的nextProps
和nextState
。如果数据没有变化,就返回false
,阻止组件重新渲染;如果数据有变化,返回true
,允许组件重新渲染。 - 对于包含大量列表项的组件,由于列表项是简单的数据展示组件,我们主要关注
props
的变化。如果列表项的数据(作为props
传递)没有改变,就阻止列表项重新渲染。
- 代码示例:
import React from 'react';
class ListItem extends React.Component {
shouldComponentUpdate(nextProps) {
// 这里假设列表项的数据只在text属性上
return this.props.text!== nextProps.text;
}
render() {
return <div>{this.props.text}</div>;
}
}
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
list: ['item1', 'item2', 'item3']
};
}
handleUpdate = () => {
// 这里模拟更新操作
this.setState({
list: ['item1', 'item2', 'item4']
});
}
render() {
return (
<div>
<button onClick={this.handleUpdate}>Update List</button>
{this.state.list.map((text, index) => (
<ListItem key={index} text={text} />
))}
</div>
);
}
}
export default List;
2. 使用 PureComponent
- 实现思路:
PureComponent
是 React 提供的一个基类,它会自动实现一个浅比较的shouldComponentUpdate
方法。- 当组件的
props
或state
发生变化时,PureComponent
会对新的props
和state
与之前的进行浅比较。如果所有的嵌套对象和数组的引用都没有改变,就不会重新渲染组件。 - 对于简单的数据展示列表项组件,只要传递给它的
props
引用没有变化,就不会重新渲染。
- 代码示例:
import React from 'react';
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
list: ['item1', 'item2', 'item3']
};
}
handleUpdate = () => {
// 这里模拟更新操作,注意要创建新的数组引用
const newList = [...this.state.list];
newList[2] = 'item4';
this.setState({
list: newList
});
}
render() {
return (
<div>
<button onClick={this.handleUpdate}>Update List</button>
{this.state.list.map((text, index) => (
<PureListItem key={index} text={text} />
))}
</div>
);
}
}
class PureListItem extends React.PureComponent {
render() {
return <div>{this.props.text}</div>;
}
}
export default List;
在实际应用中,如果数据结构比较复杂,浅比较可能无法满足需求,此时可能需要使用更复杂的比较逻辑(如深比较)在 shouldComponentUpdate
中,而 PureComponent
的浅比较就不太适用了。但对于简单的数据展示列表项,上述两种方法能有效优化性能。