前端面试题:React项目的性能优化方式有哪些

37 阅读2分钟

1. shouldComponentUpdate 生命周期方法

  • 作用:手动控制组件是否需要重新渲染。

  • 用法:通过比较新旧 props 和 state,返回 false 阻止渲染。

    jsx

    复制

    class MyComponent extends React.Component {
      shouldComponentUpdate(nextProps, nextState) {
        // 仅当特定 prop 变化时才重新渲染
        return nextProps.value !== this.props.value;
      }
      render() {
        return <div>{this.props.value}</div>;
      }
    }
    

2. React.PureComponent

  • 作用:自动对 props 和 state 进行浅比较,避免不必要的渲染。

  • 用法:继承 PureComponent 替代 Component

    jsx

    复制

    class MyComponent extends React.PureComponent {
      render() {
        return <div>{this.props.value}</div>;
      }
    }
    

3. 避免内联对象和函数

  • 问题:内联对象或函数会导致每次渲染生成新的引用,触发子组件不必要的更新。

  • 优化:将对象或函数定义为实例方法或静态变量。

    jsx

    复制

    class MyComponent extends React.Component {
      handleClick = () => { /* ... */ };
    
      render() {
        return <Child onClick={this.handleClick} />;
      }
    }
    

4. 使用 Key 优化列表渲染

  • 作用:为列表项添加唯一的 key,帮助 React 识别元素变化,减少 DOM 操作。

    jsx

    复制

    {items.map(item => (
      <li key={item.id}>{item.name}</li>
    ))}
    

5. 虚拟化长列表(Virtualization)

  • 作用:仅渲染可视区域内的列表项,减少 DOM 节点数量。

  • 工具:使用 react-window 或 react-virtualized

    jsx

    复制

    import { FixedSizeList as List } from 'react-window';
    
    const Row = ({ index, style }) => (
      <div style={style}>Row {index}</div>
    );
    
    <List height={300} itemCount={1000} itemSize={35} width={300}>
      {Row}
    </List>
    

6. 优化 Context 使用

  • 问题:Context 变化会导致所有消费组件重新渲染。
  • 优化:将 Context 拆分为多个独立的小 Context,或使用 memo 包裹子组件。

通用优化策略

1. 代码分割(Code Splitting)

  • 工具:使用 React.lazy + Suspense 或 Webpack 动态导入。

    jsx

    复制

    const LazyComponent = React.lazy(() => import('./LazyComponent'));
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
    

2. 服务端渲染(SSR)

  • 作用:加速首屏加载,提升 SEO。
  • 工具:Next.js 或自定义 SSR 实现。

3. 生产模式构建

  • 确保:使用 React 的生产版本,移除开发环境警告和调试代码。
  • 工具:Webpack 的 TerserPlugin 压缩代码,启用 Babel 的 production 模式。

4. 性能监控工具

  • React DevTools Profiler:分析组件渲染时间和次数。
  • Lighthouse:检测整体性能指标(FCP、TTI 等)。