再看React生命周期

单个React组件的生命周期应该知道了吧,不知道看这https://facebook.github.io/react/docs/react-component.html
经常用到,也经常被面试官问到

当父子组件嵌套的时候构造函数和render之间的先后关系是啥,根据dom tree结构的特点,肯定是递归调用的,对于virtual dom的diff算法有兴趣的可以看这https://supnate.github.io/react-dom-diff/index.html,做了几个可视化还是挺有意思的。下面来看下父子嵌套的生命周期吧。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
    <script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
    <script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      class A extends React.Component{
        constructor(props){super(props);console.log('A created');}
        render(){console.log('A render');return <span>A</span>}
        componentDidMount(){console.log('A rendered');}
      }

      class B extends React.Component{
        constructor(props){super(props);console.log('B created');}
        render(){console.log('B render');return <span>B<A/></span>}
        componentDidMount(){console.log('B rendered');}
      }

      class C extends React.Component{
        constructor(props){super(props);console.log('C created');}
        render(){console.log('C render');return <span>C<B/></span>}
        componentDidMount(){console.log('C rendered');}
      }
      ReactDOM.render(
        <C/>,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

console 输出

C created
C render
B created
B render
A created
A render
A rendered
B rendered
C rendered

备注

代码可以直接复制到这里 http://www.runoob.com/try/try.php?filename=try_react_hw 测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React生命周期钩子是在组件的不同阶段执行特定的操作的函数。根据引用提供的信息,React组件的生命周期可以分为实例化、存在期和销毁期。在实例化阶段,以下方法会被调用(按顺序执行):getDefaultProps、getInitialState、componentWillMount、render和componentDidMount。 在存在期阶段,组件会根据不同的情况执行不同的生命周期钩子。其中,引用提到的两个生命周期钩子getDerivedStateFromProps和getSnapshotBeforeUpdate属于存在期。 getDerivedStateFromProps是一个静态方法生命周期钩子(引用),它在组件接收新的props时被调用,并且它应该返回一个新的state对象或null值。这个钩子主要用于在props改变时更新组件的state。 getSnapshotBeforeUpdate是另一个存在期的生命周期钩子,它在组件更新之前被调用。它的返回值将作为componentDidUpdate方法的第三个参数传递。这个钩子通常用于在组件更新前保存一些信息,比如滚动位置,然后在组件更新后恢复滚动位置。 除了上述提到的钩子外,React还提供了其他的生命周期钩子函数,如componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate和componentDidUpdate等。这些钩子函数可以帮助我们在组件的不同阶段执行一些必要的操作,以便更好地控制和管理组件的行为。 综上所述,React生命周期钩子是在组件的不同阶段执行特定操作的函数,其中包括实例化阶段、存在期阶段和销毁期阶段。其中getDerivedStateFromProps和getSnapshotBeforeUpdate是在存在期阶段执行的两个重要钩子函数。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值