【发布时间】:2019-06-29 18:51:44
【问题描述】:
我有在 Gatsby 中提交表单时必须显示的成功页面。但是用户可以直接访问 /success 页面。有什么办法可以预防吗?
【问题讨论】:
我有在 Gatsby 中提交表单时必须显示的成功页面。但是用户可以直接访问 /success 页面。有什么办法可以预防吗?
【问题讨论】:
有几种方法可以做到这一点。 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 })
}
【讨论】: