组件生命周期指的是组件从初始化创建、挂载到页面、数据更新触发重新渲染,再到最终从页面卸载销毁的完整过程,用JavaScript实现组件生命周期,本质是封装一套管理这些阶段的逻辑,让开发者可以在对应阶段插入自定义操作。

组件生命周期的核心阶段
通常组件生命周期可以分为四个核心阶段,每个阶段对应不同的操作时机:
- 初始化阶段:组件实例创建,初始化自身状态和配置
- 挂载阶段:组件对应的DOM元素生成并插入到页面中
- 更新阶段:组件状态或传入的属性发生变化,触发重新渲染
- 卸载阶段:组件从页面移除,清理相关资源和事件监听
基础生命周期实现思路
我们可以通过构造函数创建组件类,在类中定义不同阶段对应的钩子函数,再在对应的逻辑节点调用这些钩子即可。下面是一个基础的实现示例:
// 基础组件类,实现生命周期管理
class BaseComponent {
constructor(props = {}) {
// 初始化阶段,调用beforeCreate钩子
this.beforeCreate && this.beforeCreate();
// 保存传入的属性
this.props = props;
// 初始化组件状态
this.state = {};
// 初始化阶段,调用created钩子
this.created && this.created();
}
// 挂载到页面的逻辑
mount(container) {
// 挂载前钩子
this.beforeMount && this.beforeMount();
// 生成组件DOM
const dom = this.render();
// 插入到容器
this.dom = dom;
container.appendChild(dom);
// 挂载后钩子,此时DOM已经存在于页面
this.mounted && this.mounted();
}
// 更新组件逻辑
setState(newState) {
// 更新前钩子
this.beforeUpdate && this.beforeUpdate();
// 合并新状态
this.state = { ...this.state, ...newState };
// 重新渲染获取新DOM
const newDom = this.render();
// 替换旧DOM
this.dom.parentNode.replaceChild(newDom, this.dom);
this.dom = newDom;
// 更新后钩子
this.updated && this.updated();
}
// 卸载组件逻辑
unmount() {
// 卸载前钩子
this.beforeUnmount && this.beforeUnmount();
// 从页面移除DOM
this.dom.parentNode.removeChild(this.dom);
// 卸载后钩子,清理资源
this.unmounted && this.unmounted();
}
// 渲染函数,子类需要重写
render() {
throw new Error('render方法需要子类实现');
}
}实际使用示例
我们可以继承上面的基础组件类,实现具体的业务组件,在对应的生命周期钩子中编写自定义逻辑:
// 继承基础组件,实现具体业务组件
class CounterComponent extends BaseComponent {
constructor(props) {
super(props);
// 初始化状态
this.state = {
count: 0
};
}
// 创建后钩子
created() {
console.log('组件实例创建完成');
}
// 挂载后钩子,绑定事件
mounted() {
console.log('组件已挂载到页面');
// 给按钮绑定点击事件
this.dom.querySelector('.btn').addEventListener('click', () => {
this.setState({
count: this.state.count + 1
});
});
}
// 更新后钩子
updated() {
console.log('组件状态更新,当前count:', this.state.count);
}
// 卸载前钩子,清理事件
beforeUnmount() {
console.log('组件即将卸载,清理事件监听');
this.dom.querySelector('.btn').removeEventListener('click', () => {});
}
// 实现渲染逻辑
render() {
const div = document.createElement('div');
div.innerHTML = `
<p>当前计数:${this.state.count}</p>
<button class="btn">点击加1</button>
`;
return div;
}
}
// 使用组件
const container = document.getElementById('app');
const counter = new CounterComponent();
// 挂载组件
counter.mount(container);
// 3秒后卸载组件
setTimeout(() => {
counter.unmount();
}, 3000);注意事项
实际实现中还需要考虑更多边界情况,比如:
- 更新阶段可以做DOM diff优化,避免不必要的全量替换DOM
- 卸载阶段需要清理所有绑定的事件、定时器等资源,避免内存泄漏
- 可以给生命周期钩子增加错误捕获逻辑,避免单个钩子报错影响整个组件流程
如果是开发复杂的前端框架,还可以在此基础上扩展更多生命周期阶段,比如捕获错误阶段的钩子、渲染阶段的中间钩子等,适配更多业务场景。
JavaScript组件生命周期前端开发生命周期钩子修改时间:2026-06-04 03:34:28