React和Vue生命周期、渲染顺序

主要就是命名不同

目录

React

组件挂载

挂载前constructor()

挂载时render()

挂载后componentDidMount():初始化节点

更新

更新时render():prop/state改变

更新后componentDidUpdate()

卸载

卸载前componentWillUnmount():清理

Vue

初始阶段:beforeCreate、created、beforeMount、mounted

更新阶段:beforeUpdate、updated

销毁阶段:beforeUnmout、unmounted


React

组件挂载

挂载前constructor()

如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数

挂载时render()

class 组件中唯一必须实现的方法。

挂载后componentDidMount():初始化节点

组件(插入 DOM 树中) 立即调用。依赖于 DOM 节点的初始化应该放在这里。

更新

更新时render():prop/state改变

它只有在 prop 或state 发生变化时才可能更新和重新渲染

更新后componentDidUpdate()

首次渲染不会执行此方法。

卸载

卸载前componentWillUnmount():清理

在组件卸载及销毁之前直接调用。在此方法中执行必要的清理操作,例如,清除 timer,取消网络请求或清除在 componentDidMount() 中创建的订阅等。

javascript 复制代码
class Welcome extends React.Component {
    state = {
        msg: 'hello world'
    }
    constructor(props){
        super(props);
        console.log('constructor');
    }
    componentDidMount = () => {
        // react中发起ajax请求的初始操作,在这个钩子中完成
        console.log('componentDidMount');
    }
    componentDidUpdate = () => {
        // 等DOM更新后触发的钩子
        console.log('componentDidUpdate');
    }
    componentWillUnmount = () => {
        console.log('componentWillUnmount');
    }
    handleClick = () => {  
        /* this.setState({
          msg: 'hi react'
        }); */
        //this.forceUpdate();
        root.unmount();   // 触发卸载组件
    }
    render(){
        console.log('render');
        return (
            <div>
                <button onClick={this.handleClick}>点击</button>
                { this.state.msg }
            </div>
        );
    }
}

Vue

初始阶段:beforeCreate、created、beforeMount、mounted

一般在,created,mounted中都可以发送数据请求 ,但是,大部分时候,会在created发送请求。因为这样可以更短的时间去响应数据。

更新阶段:beforeUpdate、updated

销毁阶段:beforeUnmout、unmounted

相关推荐
古夕29 分钟前
my-first-ai-web_问题记录03——NextJS 项目框架基础扫盲
前端·javascript·react.js
yangholmes88882 小时前
如何为 Vue 组件提供 slots 静态类型检查
vue.js
借月2 小时前
高德地图绘制工具全解析:线路、矩形、圆形、多边形绘制与编辑指南 🗺️✏️
前端·vue.js
古夕2 小时前
my-first-ai-web_问题记录02:Next.js 15 动态路由参数处理
前端·javascript·react.js
随笔记3 小时前
使用vite新搭建react项目,都需要配置什么?
前端·react.js·vite
MrSkye4 小时前
🔥React 新手必看!useRef 竟然不能触发 onChange?原来是这个原因!
前端·react.js·面试
....4924 小时前
Vue3 + Element Plus 实现可搜索、可折叠、可拖拽的部门树组件
前端·javascript·vue.js
bitbitDown5 小时前
重构缓存时踩的坑:注释了三行没用的代码却导致白屏
前端·javascript·vue.js
古夕6 小时前
my-first-ai-web_问题记录01:Next.js的App Router架构下的布局(Layout)使用
前端·javascript·react.js
Solon阿杰6 小时前
前端(react/vue)实现全景图片(360°)查看器
javascript·vue.js