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

时间:2019-06-29 18:51:44

标签: reactjs routing gatsby

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

1 个答案:

答案 0 :(得分:1)

有两种方法可以做到这一点。 One is outlined here by Gatsby并涉及创建仅客户端的路由(也就是说,Gatsby不会让React在服务器端渲染它,而是会路由到客户端/浏览器上的组件)。看起来像这样:

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 })
}