简体   繁体   English

如何通过 React Router 传递和使用查询参数?

[英]How to pass and use query parameters through react router?

I'm trying to take the value of a query parameter through the url and use it for an api call for example:我正在尝试通过 url 获取查询参数的值,并将其用于 api 调用,例如:

import { Link, useSearchParams } from "react-router-dom";

const CommonTypes = () => {
  let [searchParams, setSearchParams] = useSearchParams();

  const handleClick = (car) => {
    setSearchParams({ type: car });
  };

  return (
    <>
      <div className=" w-screen">
        <div className="container mx-auto max-w-5xl px-10 grid grid-cols-2 gap-10 py-10">
          <div className=" min-w-7xl h-fit border rounded-lg border-stone-900 p-5 pb-16 text-left ">
            <h1 className="font-semibold text-xl mb-2 font-sans">
              <span className="text-red-500 font-semibold text-xl font-sans">
                Common
              </span>{" "}
              types of choice
            </h1>
            <p className="font-sans font-medium">
              You can quickly pick a category from here by clicking on one of
              the following icons
            </p>
            <p>
              -----------------------------------------------------------------
            </p>
            <div className="grid grid-cols-3 gap-14 text-center ">
              <Link to={"/sub-cars"} onClick={handleClick(hatchback)}>
                <div className="">
                  <img src={hatchback} alt="" className="w-44 h-28"></img>
                  <p>----------------</p>
                  <span className="font-sans font-semibold text-red-500">
                    HATCHBACK
                  </span>
                </div>
              </Link>

as you can see i'm passing the value type but the url doesn't pass through a query parameter for example: http://localhost:3000/sub-cars?type=hatchback so i can use it within the new page for an api call, my other component looks like this如您所见,我正在传递值类型,但 url 没有通过查询参数,例如: http://localhost:3000/sub-cars?type=hatchback 所以我可以在新页面中使用它一个 api 调用,我的其他组件看起来像这样

const Models = () => {
  let [searchParams, setSearchParams] = useSearchParams();

  useEffect(() => {
    console.log("lol");
    console.log(searchParams.get("type"));
  }, []);

  return (
    <>
      <Navbar />
      <span>{searchParams.get("type")}</span>
    </>
  );
};

I think this is because of useSearchParams in useEffect.我认为这是因为 useEffect 中的 useSearchParams。 try it using outside of the effect and make dependency of the type in effect.尝试在效果之外使用它并依赖于有效的类型。

for example..例如..

const Models = () => {
        let [searchParams, setSearchParams] = useSearchParams();
  
    let type = searchParams.get("type")

    useEffect(() => {
      console.log("lol! the type is " , type );
     }, [type ]);

   return (
     <>
       <Navbar />
       <span>{type}</span>
     </>
   );
 };

I think you are using react router dom v6, It has some new updates, For navigating user to other page and passing search query you can do something like below, replace like this to link and import createSearchParams from react-router-dom我认为您正在使用 react router dom v6,它有一些新的更新,为了将用户导航到其他页面并传递搜索查询,您可以执行以下操作,像这样替换以链接并从 react-router-dom 导入createSearchParams

   <Link
        to={{
          pathname: "sub-cars",
          search: `?${createSearchParams({
            type: "cars"
          })}`
        }}
      >
import { useNavigate, createSearchParams, Link } from "react-router-dom";

export default function Home() {
  const navigate = useNavigate();
  return (
    <div>
      <Link
        to={{
          pathname: "sub-cars",
          search: `?${createSearchParams({
            type: "cars"
          })}`
        }}
      >
        <button>First Method - Take me to Sub Cars</button>
      </Link>

      <br />
      <br />

      <button
        onClick={() => {
          navigate({
            pathname: "sub-cars",
            search: `?${createSearchParams({
              type: "cars"
            })}`
          });
        }}
      >
        Second Method - Take me to Sub Cars
      </button>
    </div>
  );
}

You can check the codesandbox also您也可以检查代码框

编辑 admiring-flower-vtohb

you can send your desire data through location state, and catch it in the new page (where you are redirecting) by the location hook, like this:您可以通过位置 state 发送您想要的数据,并通过位置挂钩在新页面(您正在重定向的位置)中捕获它,如下所示:

<Link to={{pathname: "/sub-cars", state: {carDetails: yourValue}}} onClick={handleClick(hatchback)}>
                    <div className="">
                      <img src={hatchback} alt="" className="w-44 h-28"></img>
                      <p>----------------</p>
                      <span className="font-sans font-semibold text-red-500">
                        HATCHBACK
                      </span>
                    </div>
                  </Link>

and now on the other side现在在另一边

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

     your function {
     const location = useLocation();
      
     const [car, setCar] = useState(location.state.carDetails)

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM