react组件生命周期 react生命周期shouldcomponentupdate

   2023-03-08 学习力0
核心提示:无状态组件中没有这些生命周期方法挂载初始化props,通过类的静态属性defaultProps或者getDefaultProps函数,初始化的props会与父组件指定的props合并,最后赋值给this.propsconstructor(),或者getInitialStatecomponentWillMount(),此时dom还没渲染,在这

react组件生命周期

无状态组件中没有这些生命周期方法

挂载

  • 初始化props,通过类的静态属性defaultProps或者getDefaultProps函数,初始化的props会与父组件指定的props合并,最后赋值给this.props
  • constructor(),或者getInitialState
  • componentWillMount(),此时dom还没渲染,在这里执行的setState不会导致重绘,执行无效果
  • render()
  • componentDidMount(),在这里执行的setState会导致重绘(或称为二次渲染)

被动更新流程(父组件调用setState)

  • componentWillReceiveProps(),这时子组件的props仍然是旧的,可以在这里把新的props通过setState设置进state中,不会触发二次渲染
  • shouldComponentUpdate(),这里读取到的state是以上更新后的state
  • componentWillUpdate(),不能在这里执行setState,执行了无效果
  • render()
  • componentDidUpdate(),可以在这里进行异步的setState

主动更新流程(当前组件调用setState)

执行的函数相比上面的被动更新流程,少了一个componentWillReceiveProps方法,其余的都一样。

卸载

  • componentWillUnmount(),用于清除定时器、事件绑定

  React 官方不建议在 componentWillMount() 修改 state ,通常建议在 componentDidMount(), 如果需要设置 state 的初始状态,可以在 (es6:)constractor() 或者 (es5:)getInitialState() 中设置。

  setState是一个异步操作,修改的state必能通过this.state.xxx来马上读取,但可以在setState的第二个参数(回调函数)中读取更新后的值。执行这个函数的时候,新状态会被存放进队列中,稍后才进行状态合并,接着触发shouldComponentUpdate和render,所以连续多次的setState不会影响效率,只会触发一次render

父子组件的生命周期

 1 import React from 'react';
 2 import ReactDOM from 'react-dom';
 3 
 4 const buildClass = (name)=>{
 5     return class extends React.Component{
 6         constructor(props) {
 7             super(props);
 8             console.log( name + ' constructor');
 9         }
10         componentWillMount() {
11             console.log( name + ' componentWillMount');
12         }
13         componentDidMount() {
14             console.log( name + ' componentDidMount');
15         }
16         componentWillUnmount() {
17             console.log( name + ' componentWillUnmount');
18         }
19         componentWillReceiveProps(nextProps) {
20             console.log( name + ' componentWillReceiveProps(nextProps)');
21         }
22         shouldComponentUpdate(nextProps, nextState) {
23             console.log( name + ' shouldComponentUpdate(nextProps, nextState)');
24             return true;
25         }
26         componentWillUpdate(nextProps, nextState) {
27             console.log( name + ' componentWillUpdate(nextProps, nextState)');
28         }
29         componentDidUpdate(prevProps, prevState) {
30             console.log( name + ' componetDidUpdate(prevProps, prevState)');
31         }
32     }
33 }
34 class Child extends buildClass('Child'){
35     render(){
36         console.log('Child render')
37         return (
38             <div>child</div>
39         )
40     }
41 }
42 class Parent extends buildClass('Parent'){
43     render(){
44         console.log('Parent render')
45         return (
46             <Child />
47         )
48     }
49 }
50 ReactDOM.render(
51     <Parent />,
52     document.getElementById('root')
53 );
基础代码

 运行结果:

react组件生命周期

结论:当需要render子组件的时候,才会进入子组件的生命周期,子组件的周期结束后,再回到上级的周期。

更新组件的两种方式

1.主动更新:组件通过setState修改自己的状态。

在以上代码的基础上,往子组件中添加一个按钮,用于主动更新自己的状态:

class Child extends buildClass('Child'){
    render(){
        console.log('Child render')
        return (
            <button onClick={()=>{this.setState({data:123})}}>child</button>
        )
    }
}

点击按钮:

react组件生命周期

2.被动更新:父组件通过props把自己的state传递给子组件,父组件执行setState更新状态

父组件修改如下:

class Parent extends buildClass('Parent'){
    render(){
        console.log('Parent render')
        return (
            <div>
                <Child />
                <button onClick={()=>{this.setState({data:123})}}>Parent</button>
            </div>
        )
    }
}

 运行结果:

react组件生命周期

可见:不管父组件有没有把数据传递给子组件,只要父组件setState,都会走一遍子组件的更新周期。而且子组件被动更新会比主动更新所执行的流程多出来一个 componentWillReceiveProps 方法。

 

在以上被动更新的基础上,修改buildClass中的代码,使 shouldComponentUpdate返回false:

shouldComponentUpdate(nextProps, nextState) {
    console.log( name + ' shouldComponentUpdate(nextProps, nextState)');
    return false;
}

点击parent中的更新按钮,仅仅输出一句:

Parent shouldComponentUpdate(nextProps, nextState)

结论:只要组件在以上函数中返回false,则子组件不会进行更新re-render,所有更新流程都不执行了

class 和 createClass的区别

class 是ES6中的写法,如果想要创建组件却不使用ES6,那就使用(ES5)createClass。

前者组件的初始化在constructor中,而后者没有constructor,但额外提供了一个getInitialState方法,用于初始化state,使用createClass需要先安装:

npm install --save create-react-class

 使用:

var Counter = createClass({
    getInitialState:function(){
        console.log( ' getInitialState');
        return {
            k:123
        }
    },
    componentWillMount:function() {
        console.log( ' componentWillMount');
        console.log(this.state)
    },
    render: function() {
        return <div>{999}</div>;
    }
});

 运行结果:

react组件生命周期

以上是初始化时的第一个区别,接下来说第二个。以下两个组件的执行效果一样:

class Counter2 extends React.Component{
    render(){
        return <div>{this.props.k}</div>;
    }
}
Counter2.defaultProps = {
    k:123
};

var Counter = createClass({
    getDefaultProps:function(){
        return {
            k:123
        }
    },
    render: function() {
        return <div>{this.props.k}</div>;
    }
});

 完。

 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • React实现基于Antd密码强度校验组件示例详解
    React实现基于Antd密码强度校验组件示例详解
    目录引言效果预览组件思想组件开发引言最近在开发 Nest 和 Umi 技术栈的个人项目,在用户管理模块需要用到一个密码强度校验组件,在网上寻找一方资料,没有找到自己想要的,特此自己造轮子!效果预览组件思想既然是密码强度校验,那么强度就必须有个梯度,这
    03-16
  • 03 React快速入门(三)——实现从一个输入框中添加完数据后此输入框内容清除的功能
    03 React快速入门(三)——实现从一个输入框中
    功能描述:      我们在一个输入框输入内容,然后点击添加按钮,此输入框的内容就会添加到页面上,但是此输入框中还存在上次输入的内容,我们想在每次输入添加完成之后,此输入框中的内容就会清除,如图:   实现思路:      我们可以先在输入框上定
    03-08
  • react编译器jsxTransformer,babel
    1.JSX是什么JSX其实是JavaScript的扩展,React为了代码的可读性更方便地创建虚拟DOM等原因,加入了一些类似XML的语法的扩展。2.编译器——jsxTransformerJSX代码并不能直接运行,需要将它编译成正常的JavaScript表达式才能运行,jsxTransformer.js就是这一编
    03-08
  • G2( bizCharts ) React 绘制混合图例
    G2( bizCharts ) React 绘制混合图例
     G2( bizCharts ) React 绘制混合图例,// data-set 可以按需引入,除此之外不要引入别的包import React from 'react';import { Chart, Axis, Tooltip, Geom, Legend, Label } from 'bizcharts';import DataSet from '@antv/data-set';// 下面的代码会被作为
    03-08
  • React-多页面应用 react怎么写页面
    React-多页面应用 react怎么写页面
    1初始化项目npm init create-react-app my-app2.修改indeximport React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';ReactDOM.render(App /, document.getElementById('root')
    03-08
  • react-native start 启动错误解决方法
    ERRORError watching file for changes: EMFILE{"code":"EMFILE","errno":"EMFILE","syscall":"Error watching file for changes:","filename":null}Error: Error watching file for changes: EMFILE
    03-08
  • React兄弟组件通信(发布者-订阅者模式)
    // eventProxy.js'use strict';const eventProxy = {onObj: {},oneObj: {},on: function(key, fn) {if(this.onObj[key] === undefined) {this.onObj[key] = [];}this.onObj[key].push(fn);},one: function(key, fn) {if(this.oneObj[key] === undefined) {thi
    03-08
  • React笔记_(7)_react路由 react路由配置
    路由路由(routing)是指分组从源到目的地时,决定端到端路径的网络范围的进程。路由器当然是作为一个转发设备出现的,主要是转发数据包来实现网络互联。那么react的路由到底指的是什么呢?举个栗子~~~在网页中点击后,从A页面跳到B页面,跳转过程中url发生变
    03-08
  • react-native关闭所有黄色警告 react native st
     将以下这两句话加在index.js(入口文件)中,放在AppRegistry.registerComponent('App', () = App)之前即可1 console.ignoredYellowBox = ['Warning: BackAndroid is deprecated. Please use BackHandler instead.','source.uri should not be an empty str
    03-08
  • react中style的写法 react styles
    div style={{width: 20px; height=30px}}style的写法/div 
    03-08
点击排行