[英]How to split url in reactJs
The full url is /login?redirect=shipping
.完整的 url 是
/login?redirect=shipping
。 I want to split it into two parts like this - /login?redirect
and shipping
.我想把它分成两部分 -
/login?redirect
和shipping
。 I need the second part of the url.我需要 url 的第二部分。 that is
shipping
How can I do this in reactjs??那是
shipping
我怎么能在 reactjs 中做到这一点?
You can use useSearchParams from react-router-dom
v6.您可以使用
react-router-dom
v6 中的useSearchParams 。
You can also use URLSearchParams (Provided by Browsers)您还可以使用URLSearchParams (由浏览器提供)
In your case it would be as follows:在您的情况下,如下所示:
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: Follow useSearchParams
approach if using react and specifically react-router-dom
V6 or else go for URLSearchParams
PS:如果使用 react 并且特别是
react-router-dom
V6 ,请遵循useSearchParams
方法,否则为 URLSearchParams 使用URLSearchParams
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.