完整的url是/login?redirect=shipping
。我想把它分成两个部分——/login?redirect
和shipping
。我需要网址的第二部分。那就是shipping
我怎么能在reactjs中做到这一点??
您可以使用react-router-dom
v6中的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-dom
V6,请遵循useSearchParams
方法,否则使用URLSearchParams