如何在 React Router 中解析查询字符串 [英] How to parse a query string in React Router
问题描述
您好,我正在使用 react 路由器,我需要传递一些查询字符串参数
Hello I´m using react router and I need to pass some querystring parameters
尝试过
<Route path="/result/:type?/?filter=:filter?" exact strict component={Result}/>
我希望能捕获像
/result
/result/animals
/result/cars
/result/animals?filter=cats,dogs
/result/cars?filter=sedan,truck
正确的做法是什么?
推荐答案
对于 url 参数,比如 /animals
和 /cars
,你可以使用冒号语法 /:type
For url parameters, like /animals
and /cars
, you can use the colon syntax /:type
但是对于查询参数,比如?filter=something
,你需要解析查询字符串.
But for query parameters, like ?filter=something
, you need to parse the query string.
根据 react-router 文档:
According to react-router docs:
React Router 对你的 URL 解析方式没有任何意见询问字符串.一些应用程序使用简单的 key=value 查询字符串,但是其他人在查询字符串中嵌入数组和对象.所以这取决于你自己解析搜索字符串.
React Router does not have any opinions about how your parse URL query strings. Some applications use simple key=value query strings, but others embed arrays and objects in the query string. So it's up to you to parse the search string yourself.
在支持的现代浏览器中网址 API,你可以实例化一个 URLSearchParams
对象location.search
并使用它.
In modern browsers that support
the URL API
, you can instantiate a URLSearchParams
object from
location.search
and use that.
在不支持 URL API 的浏览器(阅读:IE)您可以使用第 3 方库,例如查询字符串.
In browsers that do not support the URL API (read: IE) you can use a 3rd party library such as query-string.
例如,在您的组件中,您将有 location
作为来自父 Route
的道具(或者您可以从 withRouter
获取它),然后您可以使用 location.search
来解析查询字符串,如下所示:
For example, in your component you will have location
as a prop from the parent Route
(or you can get it from withRouter
), you can then use location.search
to parse the query string like this:
function Parent({location}) {
let params = new URLSearchParams(location.search);
return <Child name={params.get("filter")} />;
}
欲了解更多信息:
这篇关于如何在 React Router 中解析查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!