簡體   English   中英

提交表單后直接對“謝謝”頁面做出反應

[英]React direct to a "thank you" page after submitting a form

我做了一個簡單的表單,在我點擊表單的提交按鈕后,我希望它自動重定向到我設置的“謝謝”頁面。 誰能幫我解決這個問題。 目前,這就是我認為它可能工作的方式,但它不斷彈出錯誤。 非常感謝。

const handleSubmit = event => {
    alert("Thank you for registering ");
    event.preventDefault();
    event.stopPropagation();
    handleClose();
    redirectToPage();
};
const redirectToPage = () => redirect(true);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);

if (redirect) {
    return <Link to="/thankyou" />
}
return (
  <>
        <div className="StudentForm">
            <Modal show={show} onHide={handleClose} animation={true}>
                <Modal.Header closeButton>
                    <Modal.Title>Student Information</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <Form onSubmit={handleSubmit}>
                        <Row>
                            <Col>
                                <Form.Group controlId="std_name">
                                    <Form.Control required type="text" id="std_name" name="std_name"
                                    placeholder="Student Name" />
                                </Form.Group>
                            </Col>
                        </Row>
                        <Button variant="secondary" onClick={event =>  window.location.href='/home'}>Cancel</Button>
                        <Button variant="primary" type="submit">
                            Submit
                        </Button>
                    </Form>
                </Modal.Body>
            </Modal>
        </div>
  </>
);

您想使用react-router-dom Redirect ,我建議使用useState hook 來維護一個狀態變量,該變量將確定何時重定向,而在redirectToPage您只需將其設置為true

import React,{Fragment,useState} from "react"; 
import { Redirect } from "react-router-dom";

const [redirect, setRedirect] = useState(false);

const redirectToPage = () => setRedirect(true) ;  

return (

      {redirect && (
        <Fragment>
          <Redirect to='/thankyou' />  
        </Fragment>
       )}    
       <div className="StudentForm">
       // Rest of Code
  ); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM