React生命周期函数

1、挂载阶段

1.1 constructor

挂载阶段首先执行的函数,通常用于初始化state和绑定普通函数指向。
注:this.props只有在super(props)执行后才可以调用。

constructor(props) {
    super(props);
    this.state = {}
    console.log('constructor')
}

1.2 getDerivedStateFromProps

参数props表示父组件传过来的数据,参数state表示该组件自身的state,返回值是一个对象,会更新该组件的state。

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

1.3 render

编写JSX的地方,并将JSX转化成createElement这种形式,用作生成虚拟DOM

render() {
    console.log('render');
    console.log('state', this.state);
    const {title, lists, show, changeShow} = this.props;
    return <>
        <dl className={show?"friend-group expanded":"friend-group"}>
            <dt onClick={()=>{changeShow(title)}}>{title}</dt>
            {lists.map((item, index)=>{
                return <dd key={index}>{item}</dd>
            })}
        </dl>
    </>
}

1.4 componentDidMount

在组件挂载后(插入 DOM 树中)立即调用。依赖于 DOM 节点的初始化应该放在这里。如:通过网络请求获取数据或者添加订阅

componentDidMount() {
    console.log('componentDidMount');
}

2、更新阶段

2.1 getDerivedStateFromProps

参数props表示父组件传过来的数据,参数state表示该组件自身的state,返回值是一个对象,会更新该组件的state。

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

2.2 shouldComponentUpdate

根据nextProps和this.props、nextState和this.state判断组件是否需要更新。此方法仅作为性能优化的方式而存在。 不建议在 shouldComponentUpdate() 中进行深层比较或使用 JSON.stringify()。这样非常影响效率,且会损害性能。

shouldComponentUpdate(nextProps, nextState) {
    if(this.props.count === nextProps.count) return false;
    else return true;
}

2.3 render

同1.3


2.4 getSnapshotBeforeUpdate

在最近一次渲染输出(提交到 DOM 节点)之前调用。它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)。此生命周期方法的任何返回值将作为参数传递给 componentDidUpdate

getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log(prevProps, this.props);
    console.log(prevState, this.state);
    return null;
}

2.5 componentDidUpdate

会在更新后会被立即调用。首次渲染不会执行此方法。

componentDidUpdate(prevProps, prevState, snapshot) {
    console.log(snapshot); //getSnapshotBeforeUpdate的返回值
}

3、卸载阶段

3.1 componentWillUnmount

在组件卸载及销毁之前直接调用。主要用于消除副作用,比如:清除timer、移除事件绑定。

componentWillUnmount() {
    console.log('componentWillUnmount');
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

易山易酒易诗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值