如何在reactJs中拆分url



完整的url是/login?redirect=shipping。我想把它分成两个部分——/login?redirectshipping。我需要网址的第二部分。那就是shipping我怎么能在reactjs中做到这一点??

您可以使用react-router-domv6中的useSearchParams。

您也可以使用URLSearchParams(由浏览器提供(

在您的情况下,它将如下:

import React from "react";
import { useSearchParams, useLocation } from "react-router-dom";
export const App = () => {
const [searchParams, setSearchParams] = useSearchParams();
const { search } = useLocation();
console.log(searchParams.get("redirect"));
// if it's more than 1 value for redirect i.e. redirect=shipping&redirect=shipped
console.log(searchParams.getAll("redirect")); // will return array of value
// you can use URLSearchParams also by passing search query
console.log(new URLSearchParams(search).get("redirect"));
// URLSearchParams is provided by Browser.
return <div>Search Param</div>;
};

PS:如果使用react,特别是react-router-domV6,请遵循useSearchParams方法,否则使用URLSearchParams

最新更新