首页 > 解决方案 > Next js:在后退按钮上单击页面内容未加载

问题描述

问题:在 react + nextjs 应用程序中

  1. 如果我使用链接从http://localhost:3000导航到http://localhost:3000/p/hello
  2. 刷新页面。
  3. 单击后退按钮:它转到http://localhost:3000但仍然呈现http://localhost:3000/p/hello的内容它没有加载http://localhost:3000的内容。

我正在使用“下一个”:“^8.1.0”。

导航链接

        <div>
            Click{' '}
            <Link as={`/p/hello`} href={`/postDetails?title=hello`}>
                <a>here</a>
            </Link>
            to read more
        </div>

server.js:

const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app
  .prepare()
  .then(() => {
    const server = express()
server.get('/p/:id', (req, res) => {
  const actualPage = '/postDetails'
  const queryParams = { title: req.params.id }
  app.render(req, res, actualPage, queryParams)
})

server.get('*', (req, res) => {
    //app.render(req, res, '/', queryParams)
  return handle(req, res)
})

server.listen(3000, err => {
  if (err) throw err
  console.log('> Ready on http://localhost:3000')
})
  })

  .catch(ex => {
    console.error(ex.stack)
    process.exit(1)
  })

它应该加载 index.js(localost:3000) 内容,但它显示http://localhost:3000/p/hello内容。

标签: reactjsnext.js

解决方案


这个问题绝对不是关于服务器代码的。它与下一个路由器有关,我建议您专注于路由器。

确保包含模块

import Link from 'next/link';

不带花括号试试怎么样

<div>
     Click{' '}
     <Link as='/p/hello' href='/postDetails?title=hello'>
       <a>here</a>
     </Link>
     to read more
</div>

如果你不能解决它,看看这个 npm 模块next-routes,它提供了不同的链接选项。

<Link route='postDetails' params={{title: 'hello'}}>
  <a>Hello world</a>
</Link>

https://www.npmjs.com/package/next-routes


推荐阅读