Gatsby:浏览器导航抛出 404 页面

Vin*_*rma 5 javascript navigation hyperlink reactjs gatsby

如果我使用浏览器按钮导航到路线而不是单击链接,Gatsby v3会抛出404 页面。我该如何解决这个问题?

重现步骤

  1. 使用命令启动 Gatsby 项目gatsby develop。
  2. 通过单击链接从索引页面导航到关于页面。
  3. 刷新浏览器的关于页面。
  4. 单击浏览器的后退导航。
  5. 由于未知原因,索引页会抛出 404 页面。

动图

您可以参考下面所附的 GIF,以获得更好的清晰度。

Gatsby 中 404 页面错误的 GIF

索引页:src/pages/index.js

import React from 'react';
import { Link } from 'gatsby';

const IndexPage = () => {
  return (
    <main>
      <h1>Index Page</h1>
      <Link to="/about">About Me</Link>
    </main>
  );
};

export default IndexPage;
Run Code Online (Sandbox Code Playgroud)

关于页面:src/pages/about.js

import React from 'react';
import { Link } from 'gatsby';

const AboutPage = () => {
  return (
    <main>
      <h1>About Page</h1>
      <Link to="/">Back To Home</Link>
    </main>
  );
};

export default AboutPage;
Run Code Online (Sandbox Code Playgroud)

包.json

{
  "name": "my-gatsby-site",
  "version": "1.0.0",
  "private": true,
  "description": "My Gatsby Site",
  "keywords": [
    "gatsby"
  ],
  "scripts": {
    "develop": "gatsby develop",
    "start": "gatsby develop",
    "build": "gatsby build",
    "serve": "gatsby serve",
    "clean": "gatsby clean"
  },
  "dependencies": {
    "gatsby": "^3.6.2",
    "gatsby-plugin-gatsby-cloud": "^2.8.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 0

它只发生在开发模式下。构建后,它可以正常工作。

但是您可以使用这个“脏”修复:

// gatsby-browser.js

exports.onInitialClientRender = () => {
  // dirty fix for missing popstate listener
  const GATSBY_NAVIGATE = window.___navigate || {}

  window.addEventListener('popstate', () =>
    GATSBY_NAVIGATE(window.location.pathname, { replace: true })
  )
}
Run Code Online (Sandbox Code Playgroud)

来源:https ://github.com/gatsbyjs/gatsby/issues/7261#issuecomment-414304749