React组件的常用的生命周期函数

本文深入解析React组件的生命周期,从constructor构造方法到componentWillUnmount组件卸载,详细介绍了每个生命周期阶段的功能与使用场景,包括state的初始化、组件挂载、更新、卸载等关键过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

constructor( ) 构造方法
constructor是ES6对类的默认方法,通过 new 命令生成对象实例时自动调用该方法。并且,该方法是类中必须有的,如果没有显示定义,则会默认添加空的constructor( )方法。当存在constructor的时候⚠️必须手动调用super方法。
在constructor中如果要访问this.props需要传入props,示例如下:

class MyClass extends React.component{
    constructor(props){
        super(props); // 声明constructor时必须调用super方法
        console.log(this.props); // 可以正常访问this.props
    }
}

constructor 常用来初始化state

class MyClass extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            list: this.props.List
        };
    }
}

state的值不能直接更改如果更改的话要用setState来更改,示例如下:

this.setState({
	key:this.setState.key
})

另外执行多次时,对象合并,结果是最后一个的执行结果。

componentWillMount() 组件挂载之前

在组件挂载之前调用且全局只调用一次。如果在这个钩子里可以setState,render后可以看到更新后的state,不会触发重复渲染。该生命周期可以发起异步请求,并setState。

render() 渲染组件
render()方法是必需的。当他被调用时,他将计算this.propsthis.state,并返回以下一种类型:

  1. React元素。通过jsx创建,既可以是dom元素,也可以是用户自定义的组件。
  2. 字符串或数字。他们将会以文本节点形式渲染到dom中。
  3. null,什么也不渲染
  4. 布尔值。也是什么都不渲染。
    注意:不要在render里面修改state,会触发死循环导致栈溢出。
render() {
    const {nodeResultData: {res} = {}} = this.props;
    if (isEmpty(res)) return noDataInfo;
    const nodeResult = this.getNodeResult(res);
    return (
        <div className="workspace-dialog-result">
            {nodeResult}
        </div>
    );

componentDidMount() 组件挂载完成后
组件被装配后立即调用。初始化使得DOM节点应该进行到这里。通常在这里进行ajax请求 如果要初始化第三方的dom库,也在这里进行初始化。 只有到这里才能获取到真实的dom.

componentDidMount() {
    axios.get('/auth/getTemplate').then(res => {
        const {TemplateList = []} = res;
        this.setState({TemplateList});
    });
}

shouldComponentUpdate(nextProps, nextState) 是否重新渲染
组件挂载之后,每次调用setState后都会调用shouldComponentUpdate()判断是否需要重新渲染组件默认为true(会渲染)如果shouldComponentUpdate()返回falsecomponentWillUpdate,rendercomponentDidUpdate不会被调用。可以增加条件减少不必要的渲染增加性能

componentDidUpdate() 完成组件渲染
除了首次render之后调用componentDidMount,其它render结束之后都是调用componentDidUpdate。该钩子内setState有可能会触发重复渲染,需要自行判断,否则会进入死循环。

componentDidUpdate() {
    if(condition) {
        this.setState({..}) // 设置state
    } else {
        // 不再设置state
    }
}

componentWillUnmount() 组件即将被卸载
卸载阶段的钩子函数只有一个 组件被卸载并销毁之前立即被调用。在此方法中执行任何必要的清理, 例如使定时器无效, 取消网络请求或 清理在componentDidMount中创建的任何监听。

完整的生命周期图
在这里插入图片描述
以下是完整的生命周期函数示例:

    constructor(props) {
        super(props);
        this.state = {str: "hello"};
    }

    componentWillMount() {
        alert("componentWillMount");
    }

    componentDidMount() {
        alert("componentDidMount");
    }

    componentWillReceiveProps(nextProps) {
        alert("componentWillReceiveProps");
    }

    shouldComponentUpdate() {
        alert("shouldComponentUpdate");
        return true;        // 记得要返回true
    }

    componentWillUpdate() {
        alert("componentWillUpdate");
    }

    componentDidUpdate() {
        alert("componentDidUpdate");
    }

    componentWillUnmount() {
        alert("componentWillUnmount");
    }
    render() {
        alert("render");
        return(
            <div>
                <span><h2>{parseInt(this.props.num)}</h2></span>
                <br />
                <span><h2>{this.state.str}</h2></span>
            </div>
        );
    }
}

(NZ)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值