Post

初识 React

初识 React

一、React 生命周期概述

React 组件的生命周期可以分为三个主要阶段:挂载(Mounting)更新(Updating)卸载(Unmounting)。每个阶段都有特定的方法,允许我们介入组件的生命周期。以下是 React 中的关键生命周期钩子:

1. 挂载阶段

  • constructor():组件初始化时调用,适合设置初始状态和绑定方法。
  • componentWillMount():组件挂载前调用,用于最后一刻的准备。
  • render():必须实现的方法,负责返回 JSX,定义组件的 UI。
  • componentDidMount():组件挂载到 DOM 后调用,适合执行 DOM 操作或发起 AJAX 请求。

2. 更新阶段

  • componentWillReceiveProps(nextProps):组件接收到新 props 时调用(已废弃),可用于更新状态。
  • shouldComponentUpdate(nextProps, nextState):决定是否需要更新,优化性能的关键。
  • componentWillUpdate(nextProps, nextState):更新前调用,准备更新逻辑。
  • render():再次渲染 UI。
  • componentDidUpdate(prevProps, prevState):更新后调用,适合 DOM 操作或副作用。

3. 卸载阶段

  • componentWillUnmount():组件从 DOM 移除前调用,清理定时器、事件监听等。

二、生命周期工作流程

一个典型的组件生命周期流程如下:

  1. 初始化:constructorcomponentWillMountrendercomponentDidMount
  2. 更新:componentWillReceivePropsshouldComponentUpdatecomponentWillUpdaterendercomponentDidUpdate
  3. 卸载:componentWillUnmount

三、组件化开发示例:计数器应用

通过一个简单的计数器应用,学习如何利用 React 的生命周期方法进行组件化开发。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    this.increment = this.increment.bind(this); // 绑定方法
    console.log('Constructor: 初始化状态和方法绑定');
  }

  componentWillMount() {
    console.log('componentWillMount: 组件将要挂载');
  }

  componentDidMount() {
    console.log('componentDidMount: 组件已挂载,可执行 DOM 操作');
    // 模拟 AJAX 请求
    setTimeout(() => {
      console.log('模拟数据加载完成');
    }, 1000);
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log('shouldComponentUpdate: 决定是否更新', nextState.count, this.state.count);
    return nextState.count !== this.state.count; // 仅当 count 变化时更新
  }

  componentWillUpdate(nextProps, nextState) {
    console.log('componentWillUpdate: 组件将要更新', nextState.count);
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('componentDidUpdate: 组件已更新', prevState.count);
  }

  componentWillUnmount() {
    console.log('componentWillUnmount: 组件将要卸载,清理资源');
    clearTimeout(this.timer); // 清理定时器
  }

  increment() {
    this.setState({ count: this.state.count + 1 });
  }

  decrement() {
    this.setState({ count: this.state.count - 1 });
  }

  render() {
    console.log('render: 渲染组件');
    return (
      <div>
        <h1>计数器:{this.state.count}</h1>
        <button onClick={this.increment}>加 1</button>
        <button onClick={this.decrement}>减 1</button>
      </div>
    );
  }
}

export default Counter;

使用组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React, { Component } from 'react';
import Counter from './Counter';

class App extends Component {
  state = { showCounter: true };

  toggleCounter = () => {
    this.setState({ showCounter: !this.state.showCounter });
  };

  render() {
    return (
      <div>
        <button onClick={this.toggleCounter}>切换计数器</button>
        {this.state.showCounter && <Counter />}
      </div>
    );
  }
}

export default App;

运行结果

  • 初始化:控制台依次输出 ConstructorcomponentWillMountrendercomponentDidMount,并在 1 秒后输出模拟数据加载。
  • 更新:点击“加 1”或“减 1”,触发 shouldComponentUpdatecomponentWillUpdaterendercomponentDidUpdate
  • 卸载:点击“切换计数器”隐藏组件,触发 componentWillUnmount,清理定时器。

四、生命周期在组件化开发中的应用

  1. componentDidMount
    • 适合初始化第三方库(如 Chart.js)或订阅数据流。
    • 示例:componentDidMount() { this.chart = new Chart(this.canvas); }
  2. shouldComponentUpdate
    • 优化性能,避免不必要的重新渲染。
    • 示例:只在特定 props 或 state 变化时返回 true
  3. componentWillUnmount
    • 清理资源,防止内存泄漏。
    • 示例:componentWillUnmount() { this.socket.close(); }
This post is licensed under CC BY 4.0 by the author.