您好,我正在使用 react 路由器,我需要传递一些查询字符串参数
尝试过
<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
但是对于查询参数,例如?filter=something,您需要解析查询字符串。
根据 react 路由器文档:
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.
In modern browsers that support the URL API , you can instantiate a
URLSearchParamsobject fromlocation.searchand use that.In browsers that do not support the URL API (read: IE) you can use a 3rd party library such as query-string.
例如,在您的组件中,您将拥有 location 作为来自父 Route 的 prop(或者您可以从 withRouter 获取它) ,然后您可以使用 location.search 来解析查询字符串,如下所示:
function Parent({location}) {
let params = new URLSearchParams(location.search);
return <Child name={params.get("filter")} />;
}
了解更多信息:






