如何解决禁止在Gatsby中进入成功页面
我有一个表单组件,用户可以在其中填写输入,发送点击,然后重定向到成功页面。但是,如果要手动输入url的任何人(例如domain.com/success),他都会看到该页面。如何禁用此功能?例如,如果输入domain.com/success,则重定向到/ home。这是我的代码:
import React,{ useState } from "react"
const ContactForm = () => {
const [formInput,setFormInput] = useState({
email: "",message: "",})
const onChange = e => {
setFormInput({
...formInput,[e.target.name]: e.target.value,})
}
return (
<section className="contact-form" id="contact">
<h1>Contact Us</h1>
<div className="container">
<form
method="post"
netlify-honeypot="bot-field"
data-netlify="true"
name="contact"
action="/success"
>
<input type="hidden" name="form-name" value="contact" />
<div className="form-group">
<div className="form-input">
<input
type="email"
className="form-control"
id="exampleFormControlInput1"
placeholder="Your email"
name="email"
required
value={formInput.name}
onChange={onChange}
></input>
</div>
</div>
<div className="form-group">
<div className="form-input">
<textarea
className="form-control"
id="exampleFormControlTextarea1"
rows="3"
placeholder="Your message"
name="message"
required
value={formInput.message}
onChange={onChange}
></textarea>
</div>
</div>
<button type="submit" className="button button--lg">
Send
</button>
</form>
</div>
</section>
)
}
export default ContactForm
解决方法
Gatsby有一个名为onInitialClientRender
的API挂钩,它将在初始渲染(即,当整页加载发生时)被调用,但不会在后续渲染(在客户端浏览时)被调用。要使用它,请从gatsby-browser.js
中导出一个具有该名称的函数。您可以使用此功能来检查window.location.pathname
与该路由不匹配,如果匹配,请用新位置调用navigate
来重定向用户。
import { navigate } from "gatsby"
export const onInitialClientRender = () => {
if (window.location.pathname.startsWith("/success/") {
navigate("/")
}
}
解决此问题的另一种方法是仅在客户端呈现成功页面。 Here's the documentation for this process。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。