componentDidMount
- 对应React Hooks API:
useEffect(() => { /* 副作用操作 */ }, [])
- 使用场景:
- 在类组件中,
componentDidMount
用于在组件挂载到DOM后执行一些操作,比如发起网络请求获取数据,添加事件监听器等。例如:
class MyClassComponent extends React.Component {
componentDidMount() {
fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => this.setState({ myData: data }));
}
render() {
return <div>{/* 渲染内容 */}</div>;
}
}
- 在React Hooks中,`useEffect(() => { /* 副作用操作 */ }, [])`达到相同效果,`useEffect`的第二个参数是依赖数组,传入空数组表示只在组件挂载时执行一次,例如:
import React, { useEffect, useState } from'react';
function MyFunctionalComponent() {
const [myData, setMyData] = useState(null);
useEffect(() => {
fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => setMyData(data));
}, []);
return <div>{/* 渲染内容 */}</div>;
}
- 区别:
- 类组件通过
this
来访问组件实例的属性和方法,在componentDidMount
中调用this.setState
等方法。而在Hooks中,使用useState
和useEffect
等函数式API,更简洁直观,且避免了this
指向问题。
componentDidUpdate
- 对应React Hooks API:
useEffect(() => { /* 副作用操作 */ }, [deps])
- 使用场景:
- 在类组件中,
componentDidUpdate
在组件更新后执行操作,例如根据新的props或state重新计算一些值,更新DOM等。假设我们有一个根据props变化更新图表的组件:
class ChartComponent extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.data!== this.props.data) {
// 更新图表的逻辑
}
}
render() {
return <div>{/* 渲染图表 */}</div>;
}
}
- 在React Hooks中,`useEffect(() => { /* 副作用操作 */ }, [deps])`,依赖数组`deps`指定哪些值变化时触发副作用,例如:
import React, { useEffect } from'react';
function ChartFunctionalComponent({ data }) {
useEffect(() => {
// 更新图表的逻辑
}, [data]);
return <div>{/* 渲染图表 */}</div>;
}
- 区别:
- 类组件的
componentDidUpdate
需要通过比较prevProps
和this.props
,prevState
和this.state
来判断是否需要执行操作。而Hooks通过依赖数组更清晰地声明了哪些值变化会触发副作用,使得代码意图更明确。
componentWillUnmount
- 对应React Hooks API:
useEffect(() => { return () => { /* 清理操作 */ }; }, [])
- 使用场景:
- 在类组件中,
componentWillUnmount
用于在组件从DOM中卸载前执行清理操作,比如取消网络请求,移除事件监听器等。例如,移除窗口滚动事件监听器:
class MyClassComponent extends React.Component {
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll = () => {
// 处理滚动逻辑
}
render() {
return <div>{/* 渲染内容 */}</div>;
}
}
- 在React Hooks中,`useEffect(() => { return () => { /* 清理操作 */ }; }, [])`,返回的函数就是清理函数,在组件卸载时执行,例如:
import React, { useEffect } from'react';
function MyFunctionalComponent() {
useEffect(() => {
const handleScroll = () => {
// 处理滚动逻辑
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return <div>{/* 渲染内容 */}</div>;
}
- 区别:
- 类组件的
componentWillUnmount
是一个独立的生命周期方法。而在Hooks中,清理操作作为useEffect
返回的函数,将副作用和清理操作关联在一起,逻辑更紧凑。