原文首发在个人我的博客:欢迎点此访问个人我的博客javascript
学了一段时间的react了,如今对本身学习的react的生命周期作一个简单总结(若有错误请留言指正,谢谢)
constructor可接收两个参数,获取到父组件传下来的的props,contextjava
只要组件存在constructor,就必要要写super,不然this指向会错误react
constructor(props,context) { super(props,context) }
此时组件还未渲染完成,dom还未渲染ajax
组件渲染完成,此时dom节点已经生成,能够在这里调用ajax请求算法
在接受父组件改变后的props须要从新渲染组件时须要用到这个函数浏览器
setState之后,state发生变化,组件会进入从新渲染的流程,return false能够阻止组件的更新dom
当组件进入从新渲染的流程才会进入componentWillUpdate函数函数
render是一个React组件所必不可少的核心函数,render函数会插入jsx生成的dom结构,react会生成一份虚拟dom树,在每一次组件更新时,在此react会经过其diff算法比较更新先后的新旧DOM树,比较之后,找到最小的有差别的DOM节点,并从新渲染学习
用法:this
render () { return ( <div>something</div> ) }
组件更新完毕后,react只会在第一次初始化成功会进入componentDidmount,以后每次从新渲染后都会进入这个生命周期,这里能够拿到prevProps和prevState,即更新前的props和state。
用处:
1.clear你在组建中全部的setTimeout,setInterval 2.移除全部组建中的监听 removeEventListener
父组件代码:
import React,{Component} from "react" import ChildComponent from './component/ChildComponent'//引入子组件 class App extends Component{ constructor(props,context) { super(props,context) console.log("parent-constructor") } componentWillMount () { console.log("parent-componentWillMount") } componentDidMount () { console.log("parent-componentDidMount") } componentWillReceiveProps (nextProps) { console.log("parent-componentWillReceiveProps") } shouldComponentUpdate (nextProps,nextState) { console.log("parent-shouldComponentUpdate") } componentWillUpdate (nextProps,nextState) { console.log("parent-componentWillUpdate") } componentDidUpdate (prevProps,prevState) { console.log("parent-componentDidUpdate") } render() { return "" } componentWillUnmount () { console.log("parent-componentWillUnmount") } } export default App
子组件代码:
import React,{Component} from "react" class ChildComponent extends Component{ constructor(props,context) { super(props,context) console.log("child-constructor") } componentWillMount () { console.log("child-componentWillMount") } componentDidMount () { console.log("child-componentDidMount") } componentWillReceiveProps (nextProps) { console.log("child-componentWillReceiveProps") } shouldComponentUpdate (nextProps,nextState) { console.log("child-shouldComponentUpdate") } componentWillUpdate (nextProps,nextState) { console.log("child-componentWillUpdate") } componentDidUpdate (prevProps,prevState) { console.log("child-componentDidUpdate") } render(){ return "" } componentWillUnmount () { console.log("child-componentWillUnmount") } } export default ChildComponent
浏览器中的执行结果以下图:
因此在react的组件挂载及render过程当中,最底层的子组件是最早完成挂载及更新的。
顶层父组件--子组件--子组件--...--底层子组件
底层子组件--子组件--子组件--...--顶层父组件
(若有错误,麻烦留言指正,谢谢~~)