React之 生命周期

生命周期

https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

image-20201102190349252

image-20201102190441852

组件的三个生命周期状态

  • Mount:插入真实 DOM
  • Update:被重新渲染
  • Unmount:被移出真实 DOM

React 为每个状态都提供了勾子(hook)函数

  • componentWillMount()
  • componentDidMount()
  • componentWillUpdate()
  • componentDidUpdate()
  • componentWillUnmount()

生命周期流程

  • 第一次初始化显示
ReactDOM.render(<Xxx/>, containDom)
constructor()
componentWillMount() : 将要插入回调
render() : 用于插入虚拟DOM回调
componentDidMount() : 已经插入回调
  • 每次更新 state: this.setState({})
componentWillReceiveProps(): 接收父组件新的属性
componentWillUpdate() : 将要更新回调
render() : 更新(重新渲染)
componentDidUpdate() : 已经更新回调
  • 移除组件
ReactDOM.unmountComponentAtNode(containerDom) 

componentWillUnmount() : 组件将要被移除回调

常用的方法

render 必须重写,返回一个自定义的虚拟DOM

constructor 初始化状态,绑定this(可以用箭头函数代替)

image-20201102114104319

componentWillMount()只执行一次,已经在dom树中,适合启动/设置一些监听image-20201102114113477

componentDidMount()

image-20201102141252689

componentDidUpdate() 数据更新时触发

shouldComponentUpdate(nextProps, nextState) 更新之前可以取到数据

满足条件,则渲染,否则不渲染

  • shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。

(比如判断操作是否过期 如果过期了 就return false)

(判读是否需要操作 如果当前操作和以前操作一样 就不修改 比如修改用户名)

可以在你确认不需要更新组件时使用。

重要的勾子

render(): 初始化渲染或更新渲染调用

componentDidMount(): 开启监听, 发送 ajax 请求

componentWillUnmount(): 做一些收尾工作, 如: 清理定时器

componentWillReceiveProps(): 接收父组件新的属性

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值