forthealllight / blog

📖我的博客,记录学习的一些笔记,如有喜欢,欢迎star

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React内部原理,第二部分: componentWillMount and componentDidMount

forthealllight opened this issue · comments

React内部原理,第二部分: componentWillMount and componentDidMount


第一部分我们在Feact中实现了一个基础的渲染,实现了一个最重要的生命周期函数render,在本部分中,我们会为组件添加两个生命周期函数componentWillMount和componentDidMount.

这一系列的文章包括:

  • 第一部分:基础渲染
  • 第二部分:componentWillMount and componentDidMount
  • 第三部分:基础更新
  • 第四部分:setState
  • 第三部分:transaction

修改createClass方法

在之间的createClass方法中,仅仅支持render方法,比如:

const Feact = {
    createClass(spec) {
        function Constructor(props) {
            this.props = props;
        }

        // 只使用了构造对象中的render属性,而没有用其他的属性
        Constructor.prototype.render = spec.render;

        return Constructor;
    }
}

我们仅仅需要一个简单的方式,就可以将spec中的其他方法添加到Constructor.prototype中,这样在createClass方式创建的组件不仅可以有render函数,还可以实现其他用户自定义的函数。

const Feact = {
    createClass(spec) {
        function Constructor(props) {
            this.props = props;
        }

        Constructor.prototype =
            Object.assign(Constructor.prototype, spec);

        return Constructor;
    }
    ...
}