irychen / keepalive-for-react

React KeepAlive is a component that can cache the state of the component and reuse it when needed.
MIT License
193 stars 34 forks source link

The width and height of the internal child component in keepalive-for-react are both 0. #26

Closed condorheroblog closed 1 month ago

condorheroblog commented 1 month ago

你可以点击这个链接复现:https://stackblitz.com/edit/vitejs-vite-mazfrn?file=src%2FDemo.tsx

运行如果如下图:

image

原因分析:被 KeepAlive 包裹的内部子组件的宽度和高度为 0,原因在于 CacheComponent 组件在渲染子组件内容的时候是在 useLayoutEffect 里面操作的,通过调用 renderCacheDiv,然而此时子组件的内容早已通过 createPortal 进行渲染了,子组件的上树动作先于 CacheComponent 的 useLayoutEffect 执行。


如何解决:

我认为当 async 为 false 的时候,CacheComponent 应该直接作为 children 同步渲染到 KeepAlive 组件里面。

<KeepAlive>
    {cacheNodes.map(item => {
        const { name, ele, renderCount } = item
        return (
            <CacheComponent
                async={async}
                microAsync={microAsync}
                renderCount={renderCount}
                containerDivRef={containerDivRef}
                key={name}
                errorElement={errorElement}
                active={activeName === name}
                name={name}
                destroy={destroy}
                refresh={refresh}
                cacheDivClassName={cacheDivClassName}
            >
                {ele}
            </CacheComponent>
        )
    })}
</KeepAlive>

这只是我的小想法,你认为呢?

irychen commented 1 month ago

v2.0.19 fixed this

condorheroblog commented 1 month ago

厉害 👏👏👏