类组件的生命周期函数
组件从创建到销毁的各个阶段自动执行的函数就是生命周期函数。例如:
- componentDidMount() :组件挂载完毕自动执行 - 异步获取数据。
- componentDidUpdate(prevProps, prevState, snapshot?) :React 会在你的组件更新了 props 或 state 重新渲染后立即调用它。这个方法不会在首次渲染时调用。
- componentWillUnmount():组件卸载时自动执行 - 清理副作用。
示例
import { Component, useState } from "react"
class Son extends Component {
// 生命周期函数
// 组件渲染完毕自动执行一次,在这个函数中适合发送网络请求
componentDidMount() {
console.log('组件渲染完毕,componentDidMount生命周期函数执行')
// 开启定时器
this.timer = setInterval(() => {
console.log('定时器运行中')
}, 2000)
}
// 组件卸载时自动执行,适合做副作用清理的工作,例如清除定时器、清除事件绑定
componentWillUnmount() {
console.log('子组件卸载了,componentWillUnmount函数执行了')
// 清除定时器
clearInterval(this.timer)
}
render() {
return <div>this is son</div>
}
}
function App() {
const [show, setShow] = useState(true)
return (
<>
{show && <Son />}
<button onClick={() => setShow(false)}>点击卸载子组件</button>
</>
)
}
export default App
点击按钮,卸载子组件: