gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:14:13 25 4
gpt4 key购买 nike

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

最佳答案

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

关于node.js - Nextjs 如何在转到下一页时不卸载上一页(以保持状态),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59124463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com