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

时间:2019-12-01 10:01:57

标签: node.js reactjs express next.js

我们正在Web应用程序中使用Nextjs。 我们希望保留用户访问的页面堆栈,以使组件状态保持向后导航。 我们应该怎么做? 我已经尝试过https://github.com/exogen/next-modal-pages,但它再次在后面调用了上一页的getInitialProps。

2 个答案:

答案 0 :(得分:0)

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

next的仓库中检查redux example

答案 1 :(得分:0)

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