使用react-router-dom v6提交表单后如何通过传递数据重定向到另一个页面?

在使用 react-router-dom v6 提交表单后,我试图通过传递数据重定向到另一个页面。当我点击提交时,数据将被提交,应用程序将带我到“下载 PDF”页面,表单数据也会将注册页面传递到“下载 PDF”页面。

示例代码:

确认注册.js

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

const ConfirmRegistration = () => {
  const [name, setName] = useState();
  const [confirm, setConfirm] = useState(false);

  const handleOnChange = (e) => {
    e.preventDefault();
    const value = e.target.value;
    setName(value);
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    setConfirm(true);
    console.log(name);
  };

  if (confirm) {
    return (
      <Navigate
        to={{
          pathname: "/download-pdf",
        }}
      />
    );
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type='text'
          name='name'
          placeholder='input text here'
          onChange={handleOnChange}
        />
        <button type='submit'>Submit</button>
      </form>
    </div>
  );
};

export default ConfirmRegistration;

下载PDF.js

import React from "react";

const DownLoadPdf = () => {
  return (
    <div>
      <p>DownLoad Pdf</p>
    </div>
  );
};

export default DownLoadPdf;
stack overflow How to redirect to another page with passing data after submitting form in using react-router-dom v6?
原文答案
author avatar

接受的答案

您可以使用Usenavigate而不是使用导航

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

const ConfirmRegistration = () => {
  const [name, setName] = useState();
  const [confirm, setConfirm] = useState(false);
  const navigate = useNavigate();
  const handleOnChange = (e) => {
     e.preventDefault();
     const value = e.target.value;
     setName(value);
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    setConfirm(true);
    console.log(name);
    navigate('/download-pdf', {state:// Your data})
  };

答案:

作者头像

您可以使用React路由器提供的钩子

 import { useNavigate } from "react-router-dom";

 const confirmRegistration = () => {
    const navigate = useNavigate();
    const handleSubmit = (e) => {
       ...
        navigate('/route', {state: {//pdfData}})
      };
    }

其他方式:您可以将数据存储在全球状态并从那里使用。 redux contextapi

作者头像

您正在尝试在组件之间传递数据。使用“ redux”状态管理,“上下文API”等有几种方法,然后在 DownLoadPdf 组件中您操纵数据。如果该项目是高规模的,则希望使用诸如“ Redux”之类的股票管理。但是您可以简单地通过 navigate 传递数据:

navigate('/download-pdf', {state: // The Data});