前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React关于constructor与super(props)之间的相爱相杀

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

作者头像
马克社区
发布2022-06-20 16:20:11
3000
发布2022-06-20 16:20:11
举报
文章被收录于专栏:高端IT高端IT

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

代码语言:javascript
复制
// 将生命周期方法添加到类中
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

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档