【问题标题】:Nextjs how to not unmount previous page when going to next page (to keep state)Nextjs如何在转到下一页时不卸载上一页(保持状态)
【发布时间】:2020-03-26 05:06:09
【问题描述】:

我们在我们的网络应用程序中使用 Nextjs。 我们希望保留用户访问的页面堆栈,以保持组件在返回导航时的状态。 我们应该怎么做? 我试过https://github.com/exogen/next-modal-pages,但它在后面再次调用了前几页的getInitialProps。

【问题讨论】:

    标签: node.js reactjs express next.js


    【解决方案1】:

    这是我使用自定义 _app.js 的解决方案

    import React, { useRef, useEffect, memo } from 'react'
    import { useRouter } from 'next/router'
    
    const ROUTES_TO_RETAIN = ['/dashboard', '/top', '/recent', 'my-posts']
    
    const App = ({ Component, pageProps }) => {
      const router = useRouter()
      const retainedComponents = useRef({})
    
      const isRetainableRoute = ROUTES_TO_RETAIN.includes(router.asPath)
    
      // Add Component to retainedComponents if we haven't got it already
      if (isRetainableRoute && !retainedComponents.current[router.asPath]) {
        const MemoComponent = memo(Component)
        retainedComponents.current[router.asPath] = {
          component: <MemoComponent {...pageProps} />,
          scrollPos: 0
        }
      }
    
      // Save the scroll position of current page before leaving
      const handleRouteChangeStart = url => {
        if (isRetainableRoute) {
          retainedComponents.current[router.asPath].scrollPos = window.scrollY
        }
      }
    
      // Save scroll position - requires an up-to-date router.asPath
      useEffect(() => {
        router.events.on('routeChangeStart', handleRouteChangeStart)
        return () => {
          router.events.off('routeChangeStart', handleRouteChangeStart)
        }
      }, [router.asPath])
    
      // Scroll to the saved position when we load a retained component
      useEffect(() => {
        if (isRetainableRoute) {
          window.scrollTo(0, retainedComponents.current[router.asPath].scrollPos)
        }
      }, [Component, pageProps])
    
      return (
        <div>
          <div style={{ display: isRetainableRoute ? 'block' : 'none' }}>
            {Object.entries(retainedComponents.current).map(([path, c]) => (
              <div
                key={path}
                style={{ display: router.asPath === path ? 'block' : 'none' }}
              >
                {c.component}
              </div>
            ))}
          </div>
          {!isRetainableRoute && <Component {...pageProps} />}
        </div>
      )
    }
    
    export default App
    

    要点 - https://gist.github.com/GusRuss89/df05ea25310043fc38a5e2ba3cb0c016

    【讨论】:

    【解决方案2】:

    您不能“通过不卸载来保存页面的状态”,但您可以将应用的状态保存在 _app.js 文件中,并从中重建上一页。

    检查来自next 的仓库中的redux example

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 1970-01-01
      • 2013-08-23
      • 2020-01-17
      • 2017-01-27
      • 2022-01-15
      • 2022-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多