首页 > 解决方案 > Gatsby 中的到达路由器链接闪烁页面然后消失

问题描述

我在 Gatsby 中使用 Reach Router 来设置客户端路由,如下所示,但是当我单击“关于”页面的链接时,它会从“关于”组件中闪烁内容然后消失。

import React from "react"
import { Router, Link } from "@reach/router"

import About from "../components/about.js"
import Layout from "../components/layout"

const IndexPage = () => (
  <Layout>
    <Link to="about">About</Link>
    <Router>
      <MapContainer path="/" />
      <About path="/about" />
    </Router>
  </Layout>
)

export default IndexPage

我还发现,当我import { Link } from 'gatsby'而不是 时import { Link } from '@reach/router',它会将我直接带到 Gatsby 的 404 页面。

在这两种情况下,浏览器上的后退按钮都会让我回到主页(显示 MapContainer),我认为这意味着该链接正在尝试查找不存在的静态页面。

标签: gatsbyclient-sidereach-router

解决方案


Gatsby 的路由扩展自 React 路由,因此您无需从 React 导入它。Gatsby's 具有相同的行为以及其他一些功能。

正如您所指出的,您应该使用<Link>from Gatsby 而不是@reach/router. 您的问题来自链接的路径,因为您以绝对方式发布它会导致404页面。它应该看起来像:

import React from "react"
import {Link} from 'gatsby'
import About from "../components/about.js"
import Layout from "../components/layout"

const IndexPage = () => (
  <Layout>
    <Link to="/about">About</Link>
    <Link to="/">Home</Link>
  </Layout>
)

export default IndexPage

请注意相对路径(以斜杠开头/)和路由器删除,因为它是多余的。

您可以在Gatsby 的 Link API 文档Linking between pages 文档中查看更多信息。


推荐阅读