react新版本生命周期钩子函数及用法详解

 更新时间:2021年04月28日 10:10:56   作者:河软小宝  
这篇文章主要介绍了react新版本生命周期钩子函数及用法详解,本文通过示例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

和旧的生命周期相比

在这里插入图片描述

准备废弃三个钩子,已经新增了两个钩子

React16 之后有三个生命周期被废弃(但并没有删除)

  • componentWillMount( 组件将要挂载的钩子)
  • componentWillReceiveProps(组件将要接收一个新的参数时的钩子)
  • componentWillUpdate(组件将要更新的钩子)

 新版本的生命周期新增的钩子

  •  getDerivedStateFromProps
  • 通过参数可以获取新的属性和状态
  • 该函数是静态的
  • 该函数的返回值会覆盖掉组件状态

getSnapshotBeforeUpdate

  1. 真实的DOM构建完成,但还未实际渲染到页面中。
  2. 在该函数中,通常用于实现一些附加的dom操作
  3. 该函数的返回值,会作为componentDidUpdate的第三个参数

 getDerivedStateFromProps

getDerivedStateFromProps不是给实例用的,需要将它定义为一个静态方法。且需要给一个返回值


返回值可以使 state Obj 也可以是null
返回值是 state Obj 的话直接将之前的覆盖 且无法改变
返回null 对其他任何功能都没有影响

// 从props哪里得到一个派生的状态
static getDerivedStateFromProps(props,state){
	return props
}

若 state的值 在人和时候都取决与 props 时,可以使用getDerivedStateFromProps

在这里插入图片描述

<div id="test"></div>
  <!-- 引入react核心库 -->
  <script src="../js/17.0.1/react.development.js"></script>
  <!-- 引入react-dom,用于支持react操作dom -->
  <script src="../js/17.0.1/react-dom.development.js"></script>
  <!-- 引入babel 用于将jsx 转换为 js -->
  <script src="../js/17.0.1/babel.min.js"></script>

  <script type='text/babel'>
    // 创建组件
  class Count extends React.Component{
    // 构造器
    constructor(props){
      console.log('Count---constructor')
      super(props)
      // 初始化状态
      this.state = {count:0}
    }

    // 挂载完成的钩子
    componentDidMount(){
      console.log('Count---componentDidMount')
    }

    // 卸载组件按钮的回调
    death=()=>{
      ReactDOM.unmountComponentAtNode(document.getElementById('test'))
    }

    // 实现 +1
     add =()=>{
      // 获取原状态
      const {count} = this.state
      // 更新状态
      this.setState({count:count+1})
    }

    // 强制更新按钮的回调
    force=()=>{
      this.forceUpdate()
    }

    static getDerivedStateFromProps(props,state){
      console.log('getDerivedStateFromProps',props,state)
      return props
    }

    // 控制组件更新的阀门
    shouldComponentUpdate(){
      console.log('Count---shouldComponentUpdate')
      // 如果返回值为false阀门关闭  默认为true
      return true
    }

    // 组件更新完毕的钩子
    componentDidUpdate(){
      console.log('Count---componentDidUpdate')
    }

     // 组件将要卸载的钩子
     componentWillUnmount(){
      console.log('Count---componentWillUnmount');
    }

    render(){
      console.log('Count---render')
      const {count} = this.state
      return(
        <div>
          <h2>当前求和为:{count}</h2>
          <button onClick={this.add}>点我+1</button>  
          <button onClick={this.death}>点我卸载组件</button>  
          <button onClick={this.force}>点我强制更新(不改变数据)</button>  
        </div>
      )
    }
  }
  
  // 渲染组件
    ReactDOM.render(<Count count={166}/>,document.getElementById('test'))
  </script>

执行结果

在这里插入图片描述

getSnapshotBeforeUpdate

返回值可以是null 或者 一个快照
如果是null 则没有任何影响
如果是一个快照则可以将返回值传递给componentDidUpdate 的第三个参数
componentDidUpdate 能接收的三个参数
分别是
先前的props、先前的state和getSnapshotBeforeUpdate返回的快照
prevprops、 prevstate、snapshotValue

在这里插入图片描述

<div id="test"></div>
  <!-- 引入react核心库 -->
  <script src="../js/17.0.1/react.development.js"></script>
  <!-- 引入react-dom,用于支持react操作dom -->
  <script src="../js/17.0.1/react-dom.development.js"></script>
  <!-- 引入babel 用于将jsx 转换为 js -->
  <script src="../js/17.0.1/babel.min.js"></script>

  <script type='text/babel'>
    // 创建组件
  class Count extends React.Component{
    // 构造器
    constructor(props){
      console.log('Count---constructor')
      super(props)
      // 初始化状态
      this.state = {count:0}
    }

    // 挂载完成的钩子
    componentDidMount(){
      console.log('Count---componentDidMount')
    }

    // 卸载组件按钮的回调
    death=()=>{
      ReactDOM.unmountComponentAtNode(document.getElementById('test'))
    }

    // 实现 +1
     add =()=>{
      // 获取原状态
      const {count} = this.state
      // 更新状态
      this.setState({count:count+1})
    }

    // 强制更新按钮的回调
    force=()=>{
      this.forceUpdate()
    }

    static getDerivedStateFromProps(props,state){
      console.log('getDerivedStateFromProps',props,state)
      return null
    }

    getSnapshotBeforeUpdate(){
      console.log('getSnapshotBeforeUpdate');
      return "eee"
    }

    // 控制组件更新的阀门
    shouldComponentUpdate(){
      console.log('Count---shouldComponentUpdate')
      // 如果返回值为false阀门关闭  默认为true
      return true
    }

    // 组件更新完毕的钩子
    componentDidUpdate(preProps,preState,snapshotValue){
      console.log('Count---1componentDidUpdate',preProps,preState,snapshotValue);
    }

     // 组件将要卸载的钩子
     componentWillUnmount(){
      console.log('Count---componentWillUnmount');
    }

    render(){
      console.log('Count---render')
      const {count} = this.state
      return(
        <div>
          <h2>当前求和为:{count}</h2>
          <button onClick={this.add}>点我+1</button>  
          <button onClick={this.death}>点我卸载组件</button>  
          <button onClick={this.force}>点我强制更新(不改变数据)</button>  
        </div>
      )
    }
  }
  
  // 渲染组件
    ReactDOM.render(<Count count={166}/>,document.getElementById('test'))
  </script>

总结

生命周期的三个阶段(新)

一、 初始化阶段: 由ReactDOM.render()触发—初次渲染

constructor()getDerivedStateFromPropsrender()componentDidMount()

二、 更新阶段: 由组件内部this.setSate()或父组件重新render触发

getDerivedStateFromPropsshouldComponentUpdate()render()getSnapshotBeforeUpdatecomponentDidUpdate()

三、卸载组件: 由ReactDOM.unmountComponentAtNode()触发

componentWillUnmount()

 重要的勾子

render:初始化渲染或更新渲染调用componentDidMount:开启监听, 发送ajax请求componentWillUnmount:做一些收尾工作, 如: 清理定时器

即将废弃的勾子

  1.  componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

现在使用会出现警告,下一个大版本需要加上UNSAFE_前缀才能使用,以后可能会被彻底废弃,不建议使用。

到此这篇关于react新版本生命周期钩子函数的文章就介绍到这了,更多相关react 生命周期 钩子函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • react native实现往服务器上传网络图片的实例

    react native实现往服务器上传网络图片的实例

    下面小编就为大家带来一篇react native实现往服务器上传网络图片的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • React 中如何将CSS visibility 属性设置为 hidden

    React 中如何将CSS visibility 属性设置为 hidden

    这篇文章主要介绍了React中如何将CSS visibility属性设置为 hidden,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-05-05
  • React更新渲染原理深入分析

    React更新渲染原理深入分析

    什么是re-render(重新渲染)?哪些是必要的re-render?哪些是非必要的re-render?如果你对这些问题还不是很明白,那么可以在这篇文章中找到答案
    2022-12-12
  • React项目配置axios和反向代理和process.env环境配置等问题

    React项目配置axios和反向代理和process.env环境配置等问题

    这篇文章主要介绍了React项目配置axios和反向代理和process.env环境配置等问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • 详解升级react-router 4 踩坑指南

    详解升级react-router 4 踩坑指南

    本篇文章主要介绍了详解升级react-router 4 踩坑指南,主要是对react-router 4升级的踩坑总结,有兴趣的可以了解一下
    2017-08-08
  • ReactNative-JS 调用原生方法实例代码

    ReactNative-JS 调用原生方法实例代码

    这篇文章主要介绍了ReactNative-JS 调用原生方法实例代码的相关资料,需要的朋友可以参考下
    2016-10-10
  • React中使用Mobx的方法

    React中使用Mobx的方法

    Mobx是一个前端“状态管理框架”,状态管理就是将分布在各个组件、各个模块中的状态的变化,按照一定的规则,进行统一的管理,这篇文章主要介绍了React中如何使用Mobx,需要的朋友可以参考下
    2023-02-02
  • React函数式组件Hook中的useEffect函数的详细解析

    React函数式组件Hook中的useEffect函数的详细解析

    useEffect是react v16.8新引入的特性。我们可以把useEffect hook看作是componentDidMount、componentDidUpdate、componentWillUnmounrt三个函数的组合
    2022-10-10
  • React router cache route实现缓存页面流程介绍

    React router cache route实现缓存页面流程介绍

    react-router自身没有路由缓存的特性,在5.x版本之前,我们可以基于react-router-cache-route来实现路由缓存功能。但是react-router 6.x在实现上做了比较大的变化,react-router-cache-route没有提供相应的支持
    2023-01-01
  • React高级概念之Context用法详解

    React高级概念之Context用法详解

    在React应用中,为了让数据在组件间共享,常见的方式是让它们以props的形式自顶向下传递,如果数据要在组件树不同层级共享,那么这些数据必须逐层传递直到目的地,Context如同管道,它将数据从入口直接传递到出口,使用Context能避免“prop-drilling”
    2023-06-06

最新评论