react的生命周期
react的路由v6版本与v5版本的差别
react中的HOOK
文章目录
前言
本篇介绍在react中类组件的生命周期,对于函数组件生命周期,在后面的hook中介绍,想了解更详情可以看官网react生命周期官网
一、生命周期介绍
constructor():在 React 组件挂载之前,会调用它的构造函数
componentWillMount():组件挂载之前,到18版本失效
componentDidMount():在组件挂载之后
componentWillUnmount():组件卸载之前
componentWillReceiveProps():在组件接收到props的时候触发,第一次不触发,到18版本失效
static getDericedStatieFromProps(props,state):只由props决定的数据,在这里面返回,不会被组件修改。
shouldComponentUpdate(nextProps,nextDate):当 props 或 state 发生变化时,会在渲染执行之前被调用。如果返回false,则不会调用渲染函数
componentWillUpdate():当 props 或 state 发生变化之前,到18版本失效
getSnapshotBeforeUpdate(prevProps, prevState):在最近一次渲染输出(提交到 DOM 节点)之前调用,返回值将作为参数传递给 componentDidUpdate()
componentDidUpdate():当 props 或 state 发生变化之后
static getDerivedStateFromError(error):后代组件抛出错误后被调用
对于标记了18版本失效的生命周期componentWillMount()和componentWillReceiveProps(),componentWillUpdate(),以后可能会丢弃,尽量不再使用,如果要用,那在18版本中只有加上UNSAFE_ 前缀才有效
二、引用例子
父子组件之间的生命周期顺序
挂载时:
构造函数
挂载之前
渲染页面
子构造函数
子挂载之前
子渲染页面
子挂载之后
挂载之后
数据更新时
数据发生变化后的判断
数据更新之前
渲染页面
子接收prop属性的时候触发
子数据发生变化后的判断
子数据更新之前
子渲染页面
子数据更新之后
数据更新之后
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<!-- 生产环境中不建议使用 -->
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"