17 React.js 生命周期之常用生命周期方法

在上一篇文章中,我们介绍了 React 组件的生命周期及其各个阶段。了解了生命周期的不同阶段后,接下来我们将深入探讨一些常用的生命周期方法,以及它们在组件中的实际应用。

常用生命周期方法概述

React 组件在其生命周期中提供了一些重要的方法,这些方法能够让我们在组件的不同阶段执行特定的操作。如下是一些常用的生命周期方法:

  1. constructor()
  2. componentDidMount()
  3. componentDidUpdate()
  4. componentWillUnmount()
  5. shouldComponentUpdate()

1. constructor()

constructor() 是类组件的构造函数,它通常用于初始化状态和绑定方法。在构造函数中,我们可以设置初始状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.increment = this.increment.bind(this);
}

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

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}

2. componentDidMount()

componentDidMount() 方法在组件被渲染到 DOM 后调用。这是进行如数据获取、添加订阅等副作用操作的好地方。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class UserProfile extends React.Component {
constructor(props) {
super(props);
this.state = {
user: null
};
}

componentDidMount() {
fetch('/api/user')
.then(response => response.json())
.then(data => this.setState({ user: data }));
}

render() {
const { user } = this.state;
return user ? <div>{user.name}</div> : <div>Loading...</div>;
}
}

3. componentDidUpdate()

componentDidUpdate(prevProps, prevState) 方法在组件更新后调用,允许我们对比当前和上一个状态或属性,并在必要时执行某些操作。

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
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

componentDidUpdate(prevProps, prevState) {
if (this.state.count !== prevState.count) {
console.log('Count has changed:', this.state.count);
}
}

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

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}

4. componentWillUnmount()

componentWillUnmount() 方法在组件卸载之前调用。这里可以清理一些资源,如取消网络请求或者解除事件监听等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
seconds: 0
};
}

componentDidMount() {
this.interval = setInterval(() => {
this.setState(prevState => ({ seconds: prevState.seconds + 1 }));
}, 1000);
}

componentWillUnmount() {
clearInterval(this.interval);
}

render() {
return <div>{this.state.seconds} seconds elapsed</div>;
}
}

5. shouldComponentUpdate()

shouldComponentUpdate(nextProps, nextState) 方法用于决定组件是否需要更新。可以通过返回 false 来阻止不必要的更新,提高性能。

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
class PureCounter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

shouldComponentUpdate(nextProps, nextState) {
// 仅当 count 变动时,才允许组件更新
return nextState.count !== this.state.count;
}

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

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}

总结

在本篇文章中,我们详细讲解了 React 组件中的常用生命周期方法,包括 constructor()componentDidMount()componentDidUpdate()componentWillUnmount()shouldComponentUpdate()。这些方法为我们操作组件的生命周期提供了灵活性和控制力。

下一篇文章将深入探讨 React 中的 Effect Hooks,这是一个更现代的解决方案,可以使我们更高效地管理副作用,同时也提供了更直观的方式来处理组件生命周期。希望你能继续关注!

17 React.js 生命周期之常用生命周期方法

https://zglg.work/reactjs-zero/17/

作者

IT教程网(郭震)

发布于

2024-08-15

更新于

2024-08-16

许可协议

分享转发

交流

更多教程加公众号

更多教程加公众号

加入星球获取PDF

加入星球获取PDF

打卡评论