在 Gatsby.js 中禁用直接路由到特定页面

Disable routing to a specific page directly in Gatsby.js

我有成功页面,当在 Gatsby 中提交表单时必须显示该页面。但是用户可以直接访问/success 页面。有什么办法可以预防吗?

有几种方法可以做到这一点。 One is outlined here by Gatsby 并涉及创建 client-only 路由(也就是说,Gatsby 不会让 React 渲染它 server-side,但会路由到 client/browser 上的组件)。看起来像这样:

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions

  // page.matchPath is a special key that's used for matching pages
  // only on the client.
  if (page.path.match(/^\/app/)) {
    page.matchPath = "/app/*"

    // Update the page.
    createPage(page)
  }
}

我采取的一种方法,尤其是当它不是一个特别敏感的页面时,是渲染页面,但检查渲染时的某些条件,如果条件不是,则使用 navigate使满意。

例如,如果您将 formSubmitted 存储在 AppContext 中,您可以这样做:

import React, { useContext } from "react"
import { navigate } from "gatsby"

const SuccessPage = () => {
  const { formSubmitted } = useContext(AppContext)
  return formSubmitted ? <div>Thanks!</div> : navigate("/contact", { replace: true })
}