component和virtual dom的互动

没有手撸过virtual dom的人,肯定以为component就是virtual dom了,但实际上不是,virtual dom只是个依赖,生命周期这种东西只是component自己臆想的,跟virtual dom没半毛关系。我自己写hst-virtual-dom之后,大致梳理清楚了生命周期的问题。我们来看下使用hst-virtual-dom的代码:

let vdom = new HSTVirtualDOM({ template, state })
...
vdom.create()
...
vdom.mount('#app')
...
vdom.update(newState)
...
vdom.destroy()

看到来吧,这就是在完全没有component情况下,怎么使用一个virtual dom的过程。它提供来四个方法来进行操作,create是生成vtree,这个时候只有一个和DOMtree对应的js对象,这个对象就是vtree,完全按照DOMtree的结构生成,只不过它是一个js对象。mount动作通过createElement,利用vtree创建来真正的DOM结构,并挂载到传入的selector上。create和mount这两个动作其实可以自动处理,如果实例化的时候传入来selector,就自动调用这两个方法。

update和destroy是在外部调用的,不可以自动处理。update是传入新的state,和老的state merge之后更新界面。它的处理过程是,先通过create创建一个新的vtree,通过diff算法得到新老vtree之间的差异,然后把这些差异patch到真实的DOM节点上。destroy则是把创建的真实DOM,以及它们绑定的事件监听销毁。

一个component干了什么事呢?它其实是对virtual dom的封装,完全暴露给外面的,不是virtual dom的方法,反而是一些围绕virtual dom的辅助方法:

let component = new Component() 
->
· this.getDefaultProps()
· this.getInitialState() => state
· this.componentWillMount()
->
· this.render() => template,或者说render本身已经自建了vtree
this.vdom = new HSTVirtualDOM({ template, state })
->
· this.beforeCreate() // vue
this.vdom.create()
· this.created() // vue
->
this.beforeMount() // vue
this.vdom.mount(selector)
this.mounted() // vue
this.componentDidMount()
// 下面进入存在期
this.componentWillReceiveProps()
this.shouldComponentUpdate()
this.componentWillUpdate()
this.render() => newTemplate => this.vdom.template = newTemplate
this.beforeUpdate() // vue
this.vdom.update(newState)
this.componentDidUpdate()
this.updated() // vue
// 下面进入销毁期
this.componentWillUnmount()
this.beforeDestroy() // vue
this.vdom.destroy()
this.destroyed() // vue
// 这个时候对于hst-virtual-dom来说,vdom.vtree还在,如果想要彻底销毁,只需要this.vdom = null

这样你就可以看到,一个component是多么的不起眼,只不过在调用vdom的方法前不断干一些看上去是生命周期,实际上是一些在执行vdom操作前后的普通调用而已的函数。而对于一些初学者而言,拼命的研究生命周期函数,以为即掌握了react的精髓。