Skip to content

05.常用生命周期函数源码实现

本小节实现了三个常见生命周期函数,代码演化请观看视频,这里呈现相关代码:

js
function getDomByClassComponent(vNode) {
    let { type, props, ref } = vNode;
    let instance = new type(props)
    ref && (ref.current = instance);
    let renderVNode = instance.render();
    instance.oldVNode = renderVNode
    if (!renderVNode) return null;
    let dom = createDOM(renderVNode);
    if (instance.componentDidMount) instance.componentDidMount();
    return dom
}
js
update(prevProps, prevState) {
        let oldVNode = this.oldVNode;
        let oldDOM = findDomByVNode(oldVNode);
        if (this.constructor.getDerivedStateFromProps) {
            let newState = this.constructor.getDerivedStateFromProps(this.props, this.state) || {};
            this.state = { ...this.state, ...newState };
        }
        let snapshot = this.getSnapshotBeforeUpdate && this.getSnapshotBeforeUpdate(prevProps, prevState);
        let newVNode = this.render();
        updateDomTree(oldVNode, newVNode, oldDOM)
        this.oldVNode = newVNode;
        if (this.componentDidUpdate) {
            this.componentDidUpdate(this.props, this.state, snapshot); 
        }
    }
js
function removeVNode(vNode) {
    const currentDOM = findDomByVNode(vNode);
    if (currentDOM) currentDOM.remove();
    if (vNode.classInstance && vNode.classInstance.componentWillUnmount) {
        vNode.classInstance.componentWillUnmount();
    }
}

基于 VitePress 构建