react-09React生命周期

[复制链接]
发表于 2025-9-20 01:53:04 | 显示全部楼层 |阅读模式
1.react生命周期(旧版)


1.1react初始挂载时的生命周期

1:构造器-constructor
  1. // 构造器
  2.             constructor(props) {
  3.                 console.log('1:构造器-constructor');
  4.                 super(props)
  5.                 // 初始化状态
  6.                 this.state = {count: 0}
  7.             }
复制代码
 2:组件将要挂载-componentWillMount
  1. // 组件将要挂载
  2.             componentWillMount() {
  3.                 console.log('2:组件将要挂载-componentWillMount');
  4.             }
复制代码
3:开始渲染-render
  1. render(){
  2.                 console.log('3:开始渲染-render');
  3.                 const {count} = this.state
  4.                 return(
  5.                     <div>
  6.                         <h2>当前的和为{count}</h2>
  7.                         <button onClick={this.add}>点我+1</button>
  8.                         <button onClick={this.death}>卸载DOM</button>
  9.                     </div>
  10.                 )
  11.             }
复制代码
 4:组件挂载完成-componentDidMount
  1. // 组件挂载完成
  2.             componentDidMount() {
  3.                 console.log('4:组件挂载完成-componentDidMount');
  4.             }
复制代码
 5:组件卸载-componentWillUnmount
  1. // 组件卸载
  2.             componentWillUnmount() {
  3.                 console.log('5:组件卸载-componentWillUnmount');
  4.             }
复制代码
代码实现演示

点击卸载dom后
 
 整体代码
  1. <!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>Hello,React生命周期(旧)</title></head><body>    <!-- 容器 -->    <div id="test"></div>    <!-- {/* // 引入 React焦点库 */} -->    <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>    <!-- {/* // 引入 react-dom 用于支持 react 操纵 DOM */} -->    <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>    <!-- {/* // 引入 babel:1. ES6 ==> ES5 2. jsx ==> js */} -->    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>    <!-- {/* // 引入 JSX 语法 */} -->    <script type="text/babel">        // 1. 创建组件        class Count extends React.Component {           
  2. // 构造器
  3.             constructor(props) {
  4.                 console.log('1:构造器-constructor');
  5.                 super(props)
  6.                 // 初始化状态
  7.                 this.state = {count: 0}
  8.             }                        add=()=>{                // 获取原状态                const {count} = this.state                // 状态更新                this.setState({                    count: count+1                })            }            death=()=>{                ReactDOM.unmountComponentAtNode(document.getElementById('test'))            }           
  9. // 组件将要挂载
  10.             componentWillMount() {
  11.                 console.log('2:组件将要挂载-componentWillMount');
  12.             }            
  13. // 组件挂载完成
  14.             componentDidMount() {
  15.                 console.log('4:组件挂载完成-componentDidMount');
  16.             }            
  17. // 组件卸载
  18.             componentWillUnmount() {
  19.                 console.log('5:组件卸载-componentWillUnmount');
  20.             }            
  21. render(){
  22.                 console.log('3:开始渲染-render');
  23.                 const {count} = this.state
  24.                 return(
  25.                     <div>
  26.                         <h2>当前的和为{count}</h2>
  27.                         <button onClick={this.add}>点我+1</button>
  28.                         <button onClick={this.death}>卸载DOM</button>
  29.                     </div>
  30.                 )
  31.             }        }        ReactDOM.render(<Count />,document.getElementById('test'))    </script></body></html>
复制代码
 1.2.react更新数据setState


1:shouldComponentUpdate-判定是否须要更新
  1. // 控制组件更新 默认不写此钩子函数 返回true 组件更新
  2.             shouldComponentUpdate(nextProps, nextState) {   
  3.                 console.log('1:shouldComponentUpdate-判断是否需要更新');
  4.                 return true
  5.             }
复制代码
2:componentWillUpdate-组件将要更新
  1. // 组件将要更新
  2.             componentWillUpdate(nextProps, nextState) {
  3.                 console.log('2:componentWillUpdate-组件将要更新');
  4.             }
复制代码
3:开始渲染-render
  1. render(){
  2.                 console.log('3:开始渲染-render');
  3.                 const {count} = this.state
  4.                 return(
  5.                     <div>
  6.                         <h2>当前的和为{count}</h2>
  7.                         <button onClick={this.add}>点我+1</button>
  8.                         <button onClick={this.death}>卸载DOM</button>
  9.                     </div>
  10.                 )
  11.             }
复制代码
 4:componentDidUpdate-组件更新完成
  1. // 组件更新完成
  2.             componentDidUpdate(prevProps, prevState) {
  3.                 console.log('4:componentDidUpdate-组件更新完成');
  4.             }
复制代码
5:组件卸载-componentWillUnmount
  1. // 组件卸载
  2.             componentWillUnmount() {
  3.                 console.log('5:组件卸载-componentWillUnmount');
  4.             }
复制代码
整体代码 
  1. <!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>Hello,React生命周期(旧)</title></head><body>    <!-- 容器 -->    <div id="test"></div>    <!-- {/* // 引入 React焦点库 */} -->    <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>    <!-- {/* // 引入 react-dom 用于支持 react 操纵 DOM */} -->    <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>    <!-- {/* // 引入 babel:1. ES6 ==> ES5 2. jsx ==> js */} -->    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>    <!-- {/* // 引入 JSX 语法 */} -->    <script type="text/babel">        // 1. 创建组件        class Count extends React.Component {            state = {count: 0}            add=()=>{                // 获取原状态                const {count} = this.state                // 状态更新                this.setState({                    count: count+1                })            }            death=()=>{                ReactDOM.unmountComponentAtNode(document.getElementById('test'))            }            
  2. // 组件卸载
  3.             componentWillUnmount() {
  4.                 console.log('5:组件卸载-componentWillUnmount');
  5.             }            
  6. // 控制组件更新 默认不写此钩子函数 返回true 组件更新
  7.             shouldComponentUpdate(nextProps, nextState) {   
  8.                 console.log('1:shouldComponentUpdate-判断是否需要更新');
  9.                 return true
  10.             }            
  11. // 组件将要更新
  12.             componentWillUpdate(nextProps, nextState) {
  13.                 console.log('2:componentWillUpdate-组件将要更新');
  14.             }            
  15. // 组件更新完成
  16.             componentDidUpdate(prevProps, prevState) {
  17.                 console.log('4:componentDidUpdate-组件更新完成');
  18.             }            
  19. render(){
  20.                 console.log('3:开始渲染-render');
  21.                 const {count} = this.state
  22.                 return(
  23.                     <div>
  24.                         <h2>当前的和为{count}</h2>
  25.                         <button onClick={this.add}>点我+1</button>
  26.                         <button onClick={this.death}>卸载DOM</button>
  27.                     </div>
  28.                 )
  29.             }        }        ReactDOM.render(<Count />,document.getElementById('test'))    </script></body></html>
复制代码
1.3.forceUpdate声明周期函数逼迫刷新

forceUpdate--》componentWillUpdate--》render--》componentDidUpdate--》componentWillUnmount
1.4父组件调用子组件render生命周期

componentWillReceiveProps--生命周期钩子函数---父组件调用子组件 第二次渲染,其他的调用子组件的生命周期如setState以后实行生命周期划一。
父组件A
  1. // 创建组件A--父组件
  2.         class A extends React.Component {
  3.             // 初始化状态
  4.             state={carName:'奥迪'}
  5.             // 事件
  6.             changeCarName=()=>{
  7.                 this.setState({
  8.                     carName: '宝马'
  9.                 })
  10.             }
  11.             render() {
  12.                 return (
  13.                     <div>
  14.                         <div>A组件</div>
  15.                         <button onClick={this.changeCarName}>修改车名</button>
  16.                         {/*将修改的车名传递给子组件--B*/}
  17.                         <B carName={this.state.carName} />
  18.                     </div>
  19.                 )
  20.             }
  21.         }
复制代码
子组件B
  1. // 创建组件B--子组件
  2.         class B extends React.Component {
  3.             // 生命周期钩子函数---父组件调用子组件 第二次渲染
  4.             componentWillReceiveProps() {
  5.                 console.log('b--componentWillReceiveProps');
  6.             }
  7.             render() {
  8.                 return (
  9.                     // B--props 接收父组件传递的props
  10.                     <div>B组件,接收父组件传递的props:{this.props.carName}</div>
  11.                 )
  12.             }
  13.         }
复制代码
1.5 旧版生命周期总结 

        

底子开辟中常用的生命周期钩子:

  • componentDidMount:初始化做的事变,开启定时器,发送网络请求,订阅消息。
  • render:渲染布局。
  • componentWillUnmount:收尾,关闭定时器,取消消息。

2.react生命周期(17)


componentWillMount,componentWillReceiveProps,componentWillUpdate,在新的react17上中要加前缀UNSAFE。

2.1getDerivedStateFromProps静态生命周期方法(使用频率少)

        答应组件在渲染前根据 props 的厘革更新其内部状态。它在 render() 方法之前被调用,重要用于处置惩罚那些状态依靠于 props 厘革的罕见场景。
1.留意
无法访问 this(即组件实例)
2.调用机遇
组件首次挂载时(类似于 constructor)
props 更新时(父组件重新渲染或 props 发生厘革)
逼迫更新时(this.forceUpdate())
3.返回值
必须返回一个对象来更新状态,或返回 null 表现不更新状态
返回的新状态对象会与现有状态归并
4.使用场景:
罕见情况下,状态须要依靠于 props 的厘革(比方,跟踪先前的 props 值)。
当 props 厘革时重置状态(比方,父组件通报的 prop 厘革时清空表单输入)。
5.代码展示:
  1. class Example extends React.Component {
  2.   state = {
  3.     derivedValue: 0,
  4.     prevValue: 0, // 用于存储先前的 prop 值
  5.   };
  6.   static getDerivedStateFromProps(nextProps, prevState) {
  7.     // 仅在 props.value 变化时更新状态
  8.     if (nextProps.value !== prevState.prevValue) {
  9.       return {
  10.         derivedValue: nextProps.value * 2, // 根据 prop 推导状态
  11.         prevValue: nextProps.value, // 更新存储的先前 prop 值
  12.       };
  13.     }
  14.     return null; // 无变化时不更新状态
  15.   }
  16.   render() {
  17.     return <div>Derived Value: {this.state.derivedValue}</div>;
  18.   }
  19. }
复制代码
2.2 getSnapshotBeforeUpdate (组件更新前捕获当前信息-DOM状态)

        重要用于组件更新前捕获当前信息,并将信息通报给componentDidUpdate,便于更新后举行对应的调解,
调用机遇:在render后,DOM更新前:调用机遇介于render与componentDidUpdate间。
吸收参数:吸收两个参数,prevProps(更新前的props),prevState(更新前的state)。
使用场景:捕获DOM状态(列表更新,捕获滚动位置,更新后规复滚动位置)。
componentDidUpdate共同使用:getSnapShotBeforeUpdate返回值作为它的第三个参数(snapshot)通报。在此中根据snapshot的值举行对应的操纵。
使用getSnapShotBeforeUpdate保持滚动位置稳定:
  1. import React from 'react';
  2. class ScrollingList extends React.Component {
  3.   constructor(props) {
  4.     super(props);
  5.     this.listRef = React.createRef();
  6.     this.state = {
  7.       items: ['Item 1', 'Item 2', 'Item 3'],
  8.     };
  9.   }
  10.   componentDidMount() {
  11.     setInterval(() => {
  12.       this.setState(prevState => ({
  13.         items: [`New Item ${prevState.items.length + 1}`, ...prevState.items],
  14.       }));
  15.     }, 1000);
  16.   }
  17.   getSnapshotBeforeUpdate(prevProps, prevState) {
  18.     // 捕获更新前的滚动位置
  19.     if (prevState.items.length < this.state.items.length) {
  20.       const list = this.listRef.current;
  21.       return list.scrollHeight - list.scrollTop;
  22.     }
  23.     return null;
  24.   }
  25.   componentDidUpdate(prevProps, prevState, snapshot) {
  26.     // 根据快照调整滚动位置
  27.     if (snapshot !== null) {
  28.       const list = this.listRef.current;
  29.       list.scrollTop = list.scrollHeight - snapshot;
  30.     }
  31.   }
  32.   render() {
  33.     return (
  34.       <div
  35.         ref={this.listRef}
  36.         style={{ height: '100px', overflow: 'auto', border: '1px solid black' }}
  37.       >
  38.         {this.state.items.map((item, index) => (
  39.           <div key={index}>{item}</div>
  40.         ))}
  41.       </div>
  42.     );
  43.   }
  44. }
  45. export default ScrollingList;
复制代码
 2.3总结



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表