nextjs Router.back刷新整个页面

时间:2020-05-04 19:20:59

标签: javascript react-router next.js

我有一个页面:pages/conversations/[id].tsx,其中有:

import Router, { useRouter } from 'next/router'

export default function ConversationPage() {
    const router = useRouter()
    ...
    return (
        <View style={{ flex: 1, bottom: 0 }}>
            <Appbar.Header style={{ zIndex: 10, elevation: 10}}>
                <Appbar.BackAction onPress={() => router.back()} />
                <Appbar.Content
                    title={' '}
                />
   ...

当我单击该按钮时,它将重新加载整个页面并清除状态信息。我在做什么错了?

2 个答案:

答案 0 :(得分:2)

希望这将有助于找到解决方案。

NextJS router.back()仅调用本机window.history.back()

这是源代码https://github.com/zeit/next.js/blob/d21603707edfaab292cb3190881efda9a07195cd/lib/router/router.js#L138

也许您应该间接使用Router.push()返回as参数?

<< / p>

<span onClick={() => Router.push('/post/[pid]', '/post/abc')}>
      Click me
</span> 

此处来自文档

https://nextjs.org/docs/routing/introduction#linking-between-pages https://nextjs.org/docs/api-reference/next/router#usage

链接到具有动态路径段的路线时,必须提供 href并确保路由器知道要哪个JavaScript文件 加载。

答案 1 :(得分:1)

要跟踪先前的URL,可以使用getIntialProps或getServerSideProps中req对象的req.headers中的Referer字段。

nextjs getInitialProps中的示例标头响应

headers: {
    host: 'localhost:3000',
    connection: 'keep-alive',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36',
    accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-user': '?1',
    'sec-fetch-dest': 'document',
    referer: 'http://localhost:3000/questions',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
    cookie: '_ga=GA1.1.20509028897'
  },
相关问题