0

10分钟理解React生命周期 - is橙子

 1 year ago
source link: https://www.cnblogs.com/ischengzi/p/17323944.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

学习React,生命周期很重要,我们了解完生命周期的各个组件,对写高性能组件会有很大的帮助.

React /riˈækt/ 组件的生命周期指的是组件创建销毁过程中所经历的一系列方法调用。这些方法可以让我们在不同的时刻执行特定的代码,以满足组件的需求。

React 的生命周期可以分为三个阶段:挂载阶段更新阶段卸载阶段。每个阶段都有对应的生命周期方法,如下所示:

二、生命周期三个阶段

挂载阶段

  • constructor() :/kənˈstrʌktə(r)/ 构造函数,最先被执行,我们通常在构造函数里初始化state对象或者给自定义方法绑定this
  • static getDerivedStateFromProps()static getDerivedStateFromProps(nextProps, prevState),这是个静态方法,当我们接收到新的属性想去修改state,可以使用getDerivedStateFromProps
  • render() : /ˈrendə(r)/ render函数是纯函数,只返回需要渲染的东西,不应该包含其它的业务逻辑,可以返回原生的DOM、React组件、Fragment、Portals、字符串和数字、Boolean和null等内容
  • componentDidMount():组件装载之后调用,此时可以获取到DOM节点并操作,比如对canvas,svg的操作,服务器请求,订阅都可以写在这个里面,但是记得在componentWillUnmount中取消订阅。
    componentWillUnmount中取消订阅。

1、在 componentWillUnmount 生命周期方法中,我们可以执行一些清理工作,比如取消订阅或者清除定时器等。

取消订阅是指在组件卸载之前,将之前添加的事件监听或者数据订阅取消掉,以避免内存泄漏和无效的数据处理。

具体实现方法取决于你所使用的订阅方式。如果你使用的是 React Context API 或者 Redux 等状态管理库,则可以在 componentWillUnmount 方法中取消订阅。例如,使用 React Context API 订阅状态更新的代码可能如下所示:

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.initialValue,
};
this.unsubscribe = props.subscribe(this.handleValueChange);
}
componentWillUnmount() {
this.unsubscribe();
}
handleValueChange = (newValue) => {
this.setState({ value: newValue });
};
render() {
return (
<div>
<span>Current value: {this.state.value}</span>
</div>
);
}
}

在上面的代码中,unsubscribe 方法是一个用于取消订阅的函数,它在组件创建时通过 props.subscribe 方法添加订阅,然后在组件卸载时通过 componentWillUnmount 方法进行取消订阅。

2、如果你使用的是普通的 DOM 事件监听器或者 WebSocket 等浏览器原生 API,那么你需要在组件卸载时手动移除事件监听或者关闭 WebSocket 连接等。

例如,使用 addEventListener 添加事件监听器的代码可能如下所示:

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
document.addEventListener('click', this.handleClick);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick);
}
handleClick(event) {
console.log('Clicked!', event.target);
}
render() {
return <div>Click anywhere to log the target element.</div>;
}
}

在上面的代码中,我们在组件挂载时通过 addEventListener 方法添加了一个 click 事件监听器,然后在组件卸载时通过 removeEventListener 方法移除该监听器。这样可以确保在组件卸载时不会再接收到无效的事件通知。

更新阶段

  • static getDerivedStateFromProps() /ˈstætɪk/ /dɪˈraɪvd/ /steɪt/ /prɒps/ 此方法在更新个挂载阶段都可能会调用
  • shouldComponentUpdate() shouldComponentUpdate(nextProps, nextState),有两个参数nextPropsnextState,表示新的属性和变化之后的state,返回一个布尔值,true表示会触发重新渲染,false表示不会触发重新渲染,默认返回true,我们通常利用此生命周期来优化React程序性能
  • render()  更新阶段也会触发此生命周期
  • getSnapshotBeforeUpdate() getSnapshotBeforeUpdate(prevProps, prevState),这个方法在render之后,componentDidUpdate之前调用,有两个参数prevPropsprevState,表示之前的属性和之前的state,这个函数有一个返回值,会作为第三个参数传给componentDidUpdate,如果你不想要返回值,可以返回null,此生命周期必须与componentDidUpdate搭配使用
  • componentDidUpdate() componentDidUpdate(prevProps, prevState, snapshot),该方法在getSnapshotBeforeUpdate方法之后被调用,有三个参数prevPropsprevStatesnapshot,表示之前的props,之前的state,和snapshot。第三个参数是getSnapshotBeforeUpdate返回的,如果触发某些回调函数时需要用到 DOM 元素的状态,则将对比或计算的过程迁移至getSnapshotBeforeUpdate,然后在 componentDidUpdate中统一触发回调或更新状态。

卸载阶段

  • componentWillUnmount() 当组件被卸载或者销毁了就会调用,我们可以在这个函数里去清除一些定时器,取消网络请求,清理无效的DOM元素等垃圾清理工作

这些生命周期方法按照顺序依次被调用。在挂载阶段,组件被创建并插入到 DOM 树中。在更新阶段,组件的 props 或者 state 发生改变时会触发更新,从而重新渲染组件。最后,在卸载阶段,组件被从 DOM 树中移除并销毁。

每个生命周期方法都有不同的作用,可以用来实现各种需求,比如在组件挂载时进行初始化工作、在组件更新时进行数据处理或者在组件卸载时进行清理工作等。

2762799-20230416200420428-832267779.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK