【问题标题】:Next JS Export to static HTML always redirect to home page "/" on refresh下一个 JS 导出到静态 HTML 总是在刷新时重定向到主页“/”
【发布时间】:2020-05-29 10:43:40
【问题描述】:

我正在使用 NextJSReact 创建一个博客应用程序。因为this tutorial,我已经了解了基础知识

所以我尝试实现博客应用程序。当我尝试在开发模式yarn dev 下测试它时,路由很好。但如果我构建它yarn build 并导出为静态 HTML yarn export。当我单击右侧页面上的链接时,路由会丢失,但是当我刷新浏览器时,它总是将我带回 / 页面。

为什么会这样?

这里是示例代码

Header.js 组件

import Link from 'next/link'

const linkStyle = {
  marginRight: 15
}

export default function Header() {
  return (
    <div>
      <Link href="/">
        <a style={linkStyle}>Home</a>
      </Link>
      <Link href="/about">
        <a style={linkStyle}>About</a>
      </Link>
    </div>
  )
}

MyLayout.js 组件

import Header from './Header'

const layoutStyle = {
  margin: 20,
  padding: 20,
  border: '1px solid #DDD'
}

export default function Layout(props) {
  return (
    <div style={layoutStyle}>
      <Header />
      {props.children}
    </div>
  )
}

index.js

import Layout from '../components/MyLayout.js'
import Link from 'next/link'

function getPosts() {
  return [
    { id: 'hello-nextjs', title: 'Hello Next.js' },
    { id: 'learn-nextjs', title: 'Learn Next.js is awesome' },
    { id: 'deploy-nextjs', title: 'Deploy apps with ZEIT' }
  ]
}

const PostLink = ({ post }) => (
  <li>
    <Link href="/p/[id]" as={`/p/${post.id}`}>
      <a>{post.title}</a>
    </Link>
    <style jsx>{`
      li {
        list-style: none;
        margin: 5px 0;
      }

      a {
        text-decoration: none;
        color: blue;
        font-family: 'Arial';
      }

      a:hover {
        opacity: 0.6;
      }
    `}</style>
  </li>
)

export default function Blog() {
  return (
    <Layout>
      <h1>My Blog</h1>
      <ul>
        {getPosts().map(post => (
          <PostLink key={post.id} post={post} />
        ))}
      </ul>
    </Layout>
  )
}

package.json

{
  "name": "hello-next",
  "version": "1.0.0",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start -p $PORT",
    "export": "next export"
  },
  "license": "ISC",
  "dependencies": {
    "next": "latest",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-markdown": "^4.0.6"
  }
}

编辑:我遵循了本指南nextjs.org/learn/basics/deploying-a-nextjs-app。但我使用“部署到您自己的环境”步骤。因此与此 repo github.com/zeit/next-learn-demo/tree/master/8-deploying

的结构基本相同

【问题讨论】:

标签: reactjs next.js


【解决方案1】:

我通过将以下内容添加到 next.config.js 解决了这个问题:

module.exports = {
  exportTrailingSlash: true,
}

https://nextjs.org/docs/api-reference/next.config.js/exportPathMap#adding-a-trailing-slash

我猜这取决于您的网络服务器。

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 2021-12-06
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多