简体   繁体   中英

nextjs Router.back does a full page refresh

I have a page: pages/conversations/[id].tsx , which has:

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={' '}
                />
   ...

When I click that, it reloads the entire page and wipes out the state information. What am I doing wrong?

Hope this will be helpful in finding asolution.

NextJS router.back() only calls the native window.history.back()

Here is the source code https://github.com/zeit/next.js/blob/d21603707edfaab292cb3190881efda9a07195cd/lib/router/router.js#L138

Maybe you should use Router.push() indirectly to go back using the as param?

<

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

Here is from the documentation

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

When linking to a route with dynamic path segments you have to provide href and as to make sure the router knows which JavaScript file to load.

To track the previous url, you can use the referer field in req.headers from the req object in getIntialProps or getServerSideProps.

Sample header response in 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'
  },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM