禁止在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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...