关于react.js:React源码constructor

3次阅读

共计 1559 个字符,预计需要花费 4 分钟才能阅读完成。

该文章的 demo


import React from './react-dev/react';

import {render} from './react-dev/react-dom';

class App extends React.Component {constructor(props) {super(props);

this.state = {count: 0};

this.handleClick = this.handleClick.bind(this);

}

handleClick(event) {console.log('hello');

console.log('event', event);

this.setState((state) => {console.log('sasa');

return {count: state.count + 1};

});

}

render() {

return [<button key="1" onClick={this.handleClick}>Update counter</button>,

<span key="2">{this.state.count}</span>

]

}

}

render(<App />, document.getElementById('app'));

咱们写 react 代码的时候每次在写 construtor 的时候写super(props),其实它做了什么真不知道,依据官网文档

在为 React.Component 子类实现构造函数时,应在其余语句之前前调用 super(props)。否则,this.props 在构造函数中可能会呈现未定义的 bug。

从源码的角度看是怎么回事呢,通过命令编译下面的 demo


./node_modules/.bin/babel src/index.jsx

当有 super(props) 的时候


function App(propss) {

var _this;

_classCallCheck(this, App);

// 留神这行

_this = _super.call(this, propss);

_this.state = {count: 0};

_this.handleClick = _this.handleClick.bind(_assertThisInitialized(_this));

return _this;

}

当没有的时候


function App(props) {

var _this;

_classCallCheck(this, App);

// super(props);

_this.state = {count: 0};

_this.handleClick = _this.handleClick.bind(_assertThisInitialized(_this));

return _possibleConstructorReturn(_this);

}

看出什么了吗?super(props)就是去定义 this 的,如果没有的话,this 就没有值,前面的代码都会报错。

其实我感觉下面官网的说法应该更硬气一点: 写 constructor 时必须调用 super 办法????

另外 props 又是做什么的呢,其实就是绑定从调用者那边传入的 props 到 this 对象上。

另外当你调用 super 时,如果你的编辑器有代码提醒的话就能够看到其实 super 是能够传入props, context, updater 3 个变量的,不过个别应用就是用第一个,context 在这里也是很少用的

更多文章

referrence:

  1. https://www.nstinfotech.com/difference-between-super-and-super-props-reactjs/
  2. https://overreacted.io/zh-hans/why-do-we-write-super-props
正文完
 0