React关于constructor与super(props)之间的相爱相杀

我们先把菜鸟教程的一段代码拿过来分析一下。下面这段代码是用了将生命周期方法添加到类中实现时钟效果。

// 将生命周期方法添加到类中
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};//初始化
  }
//开始
  componentDidMount() {
     this.timerID = setInterval(
       () => this.tick(),
       1000
     );
   }
//销毁
   componentWillUnmount() {
     clearInterval(this.timerID);
   }
//重新改变date值
   tick() {
     this.setState({
       date: new Date()
     });
   }
//注册组件
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>现在是 {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
//····································
//挂载到实例
ReactDOM.render(
  <Clock />,
  document.getElementById('example')
);

好,下面我们就再写一段原生js实现上述效果,对比一下。

function timejs () {
this.timer = null;
var time1= new Date();
var time2=time1.toLocaleTimeString()
document.getElementById(“time”).innerHTML = time2 //这里的id为time我这里没写,自己写上即可

 

}
var timer=setInterval(timejs,1000);

 

嗯,我们可以看到原生js代码量比React少得多。
下面我们为了方便起见。将React中的代码写为A,将原生JS中的代码写为B。
B中的timejs()相当于A中的tick(),不同的是A需要初始化,所以A中有 this.state = {date: new Date()};
这时你会发现super(props)是什么鬼?我注释掉行不行?答案是不行的。你会看到下面这段鲜红的BUG。
在这里插入图片描述

错误的含义是this之前不能没有super(props)
那么super到底是什么呢

 

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/119882639

posted @ 2022-06-16 16:40  忘川信使  阅读(41)  评论(0编辑  收藏  举报