Nextjs 如何在转到下一页时不卸载上一页(以保持状态)

Nextjs how to not unmount previous page when going to next page (to keep state)

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

您不能 "save the state of the page by not un-mounting it",但您可以将应用程序的状态保存在 _app.js 文件中,然后从中重建上一页。

检查 next 仓库中的 redux example

这是我的自定义解决方案 _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