我有一个表单组件,用户可以在其中填写输入,发送点击,然后重定向到成功页面。但是,如果要手动输入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
答案 0 :(得分:0)
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。