微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

禁止在Gatsby中进入成功页面

如何解决禁止在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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?