CJY0208 / react-activation

Hack <KeepAlive /> for React
https://www.npmjs.com/package/react-activation
MIT License
1.78k stars 140 forks source link

配合@loadable/component使用,不生效 #287

Closed CurryHan closed 11 months ago

CurryHan commented 11 months ago
  const ProudctIndex = loadable(()=>import('../pages/productmgr/product/index'),{
    cacheKey: props => '/productmgr/product/index',
})      

return (
<Route
              key={'/productmgr/product/index'}
              exact
              path={'/productmgr/product/index'}
              render={() => {
                return <ErrorBoundary>
                    <KeepAlive cacheKey={'/productmgr/product/index'} saveScrollPosition={true}>
                      <ProudctIndex pageTitle='产品' pageName='product' url={'/productmgr/product/index'} />
                    </KeepAlive>
                </ErrorBoundary>
              }}
            />
)
CJY0208 commented 11 months ago
function Page() {
  const ProudctIndex = loadable(...)      

  return (
    <KeepAlive>
      <ProudctIndex />
    </KeepAlive>
  )
}

to

const ProudctIndex = loadable(...) 

function Page() {
  return (
    <KeepAlive>
      <ProudctIndex />
    </KeepAlive>
  )
}
CurryHan commented 11 months ago

可以了 谢谢! 顺便请教下 为什么这样可以,是因为Page渲染了,导致动态加载的组件也重新渲染了吗?

CJY0208 commented 11 months ago

之前那样写,每次 render 都会调用 loadable,生成一个新的 ProudctIndex 组件构造器,对于 react 来说,会认为这是个全新的组件,会导致每次 render 之后, react 都会卸载并重建这个组件

可以起到相同作用的写法是

function Page() {
  const ProudctIndex = React.useMemo(() => loadable(...), [])      

  return (
    <KeepAlive>
      <ProudctIndex />
    </KeepAlive>
  )
}
CurryHan commented 11 months ago

谢谢