要将参数传递到其他页面,可以使用React Router库中的props.history.push方法来导航到其他页面,并将参数作为查询字符串传递。

首先,您需要在要导航到的页面中定义一个查询字符串参数接收器。您可以使用React Router库中的useLocation钩子来访问查询字符串参数。

在要接收参数的页面中,您可以使用以下代码:

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

function MyComponent() {
  const location = useLocation();
  const myParam = new URLSearchParams(location.search).get("myParam");

  return (
    <div>
      <h1>My Component</h1>
      <p>My param is: {myParam}</p>
    </div>
  );
}

然后,在发送请求的组件中,您可以使用props.history.push方法导航到要接收查询字符串参数的页面,并将参数作为查询字符串传递。

例如,您可以使用以下代码:

import axios from "axios";
import { useHistory } from "react-router-dom";

function MySendingComponent() {
  const history = useHistory();

  function handleClick() {
    axios.get("/my-api-endpoint", {
      params: {
        myParam: "Hello, world!"
      }
    })
    .then(() => {
      history.push("/my-receiving-page?myParam=Hello%2C%20world%21");
    });
  }

  return (
    <div>
      <button onClick={handleClick}>Send Request</button>
    </div>
  );
}

在此示例中,我们发送一个带有myParam参数的GET请求,并在请求成功后导航到接收页面,并将myParam作为查询字符串传递。注意,我们必须使用encodeURIComponent函数对查询字符串参数进行编码,以确保它们可以正确传递。

react函数组件axios定义params传参到其他页面

原文地址: https://www.cveoy.top/t/topic/bjfL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录