当前位置: 首页 > news >正文

react的生命周期

目录

一、初始化阶段

constructor() 

static getDerivedStateFromProps()

 componentWillMount()  /  UNSAFE_componentWillMount()

render():

componentDidMount()

二、运行阶段

componentWillUpdate() / UNSAFE_componentWillUpdate()

render()

getSnapshotBeforeUpdate()

componentDidUpdate()

componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()

shouldComponentUpdate()

三、 销毁阶段

 componentWillUnmount()

四、异常错误捕抓

static getDerivedStateFromError()

componentDidCatch()


 以下方法介绍的顺序为生命周期执行的顺序:

一、初始化阶段

  • constructor() 

        构造函数,参数props为父组件传过来的属性,必须加上super来继承,初始化阶段只执行一次。注意,不要在constructor中使用setState,因为此时的state是未定义的,无法进行setState;也不要在constructor的state中用props来进行赋值,因为可以直接使用this.props,如果这样做则会导致一些不可控的问题出现

  constructor(props){super(props)this.state = {text: '我是爱坤',}}
  • static getDerivedStateFromProps()

        getDerivedStateFromProps(props,state),props参数为父组件传过来的属性值,state为自身内部改变后的state。

        与UNSAFE_componentWillReceiveProps相类似,但不同的前者是在父组件渲染时会触发,而getDerivedStateFromProps()方法在父组件、子组件、自身进行渲染时都会进行触发,也包括自身的初始化阶段。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容,适用于状态值的修改

  static getDerivedStateFromProps(props,state){console.log("getDerivedStateFromProps-"+JSON.stringify(props)+"--"+JSON.stringify(state))return null}

 

 

  •  componentWillMount()  /  UNSAFE_componentWillMount()

        render调用之前会执行,最后一次修改状态的机会。此方法已被遗弃不做过多介绍

  • render():

        页面渲染,只能访问this.props和this.state,不允许修改状态和DOM输出,class 组件中唯一必须实现的方法,需保持保持render()为纯函数

  • componentDidMount()

        成功render并渲染完成真实的DOM之后立即触发,可以修改DOM。通常用于axios网络请求获取数据,可以直接在内部使用this.setState方法,此时整个初始化阶段render将会被调用两遍。


二、运行阶段

  • componentWillUpdate() / UNSAFE_componentWillUpdate()

        render函数重新渲染之前将会调用一次,不能修改属性和状态。此方法已被遗弃,不作过多介绍。

  • render()

        页面渲染,只能访问this.props和this.state,不允许修改状态和DOM输出,class 组件中唯一必须实现的方法,需保持保持render()为纯函数

  • getSnapshotBeforeUpdate()

        getSnapshotBeforeUpdate(prevProps,prevState),prevProps:组件重新渲染时立即保存下来的父组件旧属性;prevState:组件重新渲染时立即保存下来的内部组件的状态值。

        此方法更替了componentWillUpdate()方法,在render函数挂载与渲染之间调用,用于捕抓DOM节点要修改时的数据。

 getSnapshotBeforeUpdate(prevProps, prevState) {// 我们是否在 list 中添加新的 items ?// 捕获滚动​​位置以便我们稍后调整滚动位置。if (prevProps.list.length < this.props.list.length) {const list = this.listRef.current;return list.scrollHeight - list.scrollTop;}return null;}
  • componentDidUpdate()

        componentDidUpdate(prevProps,prevState,snapShot) prevProps:父组件旧属性值;prevState:自身的旧状态值;snapShot:此参数getSnapshotBeforeUpdate的返回值。

        在render函数渲染完成后调用,首次渲染不会执行此方法。可以修改DOM,适用于判断数据是否已更新,可以使用this.setState(),不过需要给与终止条件,否则会造成死循环。

class ScrollingList extends React.Component {constructor(props) {super(props);this.listRef = React.createRef();}getSnapshotBeforeUpdate(prevProps, prevState) {// 我们是否在 list 中添加新的 items ?// 捕获滚动​​位置以便我们稍后调整滚动位置。if (prevProps.list.length < this.props.list.length) {const list = this.listRef.current;return list.scrollHeight - list.scrollTop;}return null;}componentDidUpdate(prevProps, prevState, snapshot) {// 如果我们 snapshot 有值,说明我们刚刚添加了新的 items,// 调整滚动位置使得这些新 items 不会将旧的 items 推出视图。//(这里的 snapshot 是 getSnapshotBeforeUpdate 的返回值)if (snapshot !== null) {const list = this.listRef.current;list.scrollTop = list.scrollHeight - snapshot;}}render() {return (<div ref={this.listRef}>{/* ...contents... */}</div>);}
}
  • componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()

        父组件重新渲染时会触发,此方法已被遗弃,不做过多介绍。

  • shouldComponentUpdate()

        shouldComponentUpdate(nextProps,nextState),nextProps:更新后的属性值;nextState:更新后的状态值。返回false会阻止render函数的调用,主要用于提升性能。父组件状态发生改变时,其父组件下的所有子组件都会被重新渲染一遍,当组件过多时就会造成性能下降。有时候只需要对其中的几个子组件进行渲染而不是所有,因此就可以使用此方法来进行阻止。

import ReactDOM from 'react-dom/client';
import React, { Component } from 'react'class Ikun extends Component {constructor(props) {super(props)this.state = {list: [{ id: 1, text: "111" }, { id: 2, text: "222" }, { id: 3, text: "333" }, { id: 4, text: "444" }, { id: 5, text: "555" }],index: 1}}render() {return (<><button onClick={() => {this.state.index <5 ?  this.setState({ index: this.state.index + 1 }) : this.setState({ index: 1 }) }}>切换</button>{this.state.list.map((item) =><A key={item.id} {...item} index={this.state.index} />)}</>)}
}class A extends Component {shouldComponentUpdate(nextProps,nextState){if(nextProps.id ==nextProps.index || nextProps.id == nextProps.index-1)return trueelsereturn false}render() {return (<>{console.log("我是A组件,判断是否被调用" + this.props.id)}<li style={this.props.id === this.props.index ? { backgroundColor: "green" } : {}}>我是一个子组件{this.props.text}</li></>)}
}const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Ikun />
);

        如下:每次更新父组件state时,只对需要改变的组件进行调用render

 

三、 销毁阶段

  •  componentWillUnmount()

        在删除组件之前进行清理操作,比如计时器、订阅、事件监听器等。

import ReactDOM from 'react-dom/client';
import React, { Component } from 'react'class Ikun extends Component {constructor(props) {super(props)this.state = {count: 0}}render() {return (<><button onClick={() => this.time}>启动</button><div>计时器{this.state.count}</div></>)}time = setInterval(() => {this.setState({ count: this.state.count + 1 })console.log(this.state.count)}, 1000)componentWillUnmount(){this.time=null}}const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Ikun />
);

四、异常错误捕抓

  • static getDerivedStateFromError()

        static getDerivedStateFromError(error)  此生命周期会在后代组件抛出错误后被调用。 它将抛出的错误作为参数,并返回一个值以更新 state

class ErrorBoundary extends React.Component {constructor(props) {super(props);this.state = { hasError: false };}static getDerivedStateFromError(error) {    // 更新 state 使下一次渲染可以显降级 UI    return { hasError: true };  }render() {if (this.state.hasError) {      // 你可以渲染任何自定义的降级  UI      return <h1>Something went wrong.</h1>;    }return this.props.children;}
}
  • componentDidCatch()

        componentDidCatch(error,info) error :抛出的错误 ; info:带有 componentStack key 的对象。在“提交”阶段被调用。

class ErrorBoundary extends React.Component {constructor(props) {super(props);this.state = { hasError: false };}static getDerivedStateFromError(error) {// 更新 state 使下一次渲染可以显示降级 UIreturn { hasError: true };}componentDidCatch(error, info) {// "组件堆栈" 例子://   in ComponentThatThrows (created by App)//   in ErrorBoundary (created by App)//   in div (created by App)//   in ApplogComponentStackToMyService(info.componentStack);}render() {if (this.state.hasError) {// 你可以渲染任何自定义的降级 UIreturn <h1>Something went wrong.</h1>;}return this.props.children;}
}

 

http://www.lryc.cn/news/23110.html

相关文章:

  • scanpy 单细胞分析API接口使用案例
  • 【Vue3 第二十一章】Teleport组件传送
  • 在 Windows Subsystem for Linux (WSL2) 的 Ubuntu 系统上配置 Vulkan 开发环境
  • 放苹果HJ61
  • Windows下,OPC UA移植,open62541移植
  • 【Tomcat与Servlet篇1】认识Tomcat与Maven
  • C++类和对象:拷贝构造函数和运算符重载
  • 【IntelliJ IDEA】idea plugins搜索不出来,如何找到插件的解决方案
  • 移动端自动化测试(一)appium环境搭建
  • 5 逻辑回归及Python实现
  • 技术干货 | Modelica建模秘籍之状态变量
  • LeetCode 2574. 左右元素和的差值
  • rollup环境配置
  • 二分查找与二分答案、递推与递归、双指针、并查集和单调队列
  • 如何进行域名购买,获取免费ssl证书,使用springboot绑定ssl证书
  • LabVIEW网络服务安全2
  • java动态代理
  • Python 简单可变、复杂可变、简单不可变、复杂不可变类型的copy、deepcopy的行为
  • QML Item
  • 使用xca工具生成自签证书
  • Unity IOS 通过命令行导出IPA
  • 「架构」全链路异步模式
  • CleanMyMac4.20最新版新增功能及电脑清理垃圾使用教程
  • Vue2的tsx开发入门完全指南
  • GLSL shader学习系列1-Hello World
  • Codeforces Round #851 (Div. 2)(A~D)
  • 内存保护_1:Tricore芯片MPU模块介绍
  • Vue3 -- PDF展示、添加签名(带笔锋)、导出
  • 行测-判断推理-图形推理-样式规律-属性规律-曲直性
  • idea集成Alibaba Cloud Toolkit插件