7. 重构 function component

35 阅读1分钟

优化一下之前的代码

  • function component的时候走一个函数 ,正常节点的时候走一个函数
function updateFunctionComponent (fiber) {
    const children = [fiber.type(fiber.props)]
    initChildren(fiber, children)
}
​
function updateHostComponent (fiber) {
    if (!fiber.dom) {
        const dom = createDom(fiber.type)
        fiber.dom = dom
        updateProps(dom, fiber.props)
    }
    const children = fiber.props.children
    initChildren(fiber, children)
} 
​
function performWorkOfUnit(fiber) {
    const isFunctionComponent = typeof fiber.type === 'function'
    if(isFunctionComponent) {
        updateFunctionComponent(fiber)
    } else {
        updateHostComponent(fiber)
    }
​
    if (fiber.child) {
        return fiber.child
    }
​
    let nextFiber = fiber;
    while(nextFiber) {
        if(nextFiber.sibling) return nextFiber.sibling;
        nextFiber = nextFiber.parent
    }
​
    return fiber.parent?.sibling
}