如何在 React Router 中解析查询字符串

han*_*ome 13 javascript reactjs react-router

你好,我正在使用 react 路由器,我需要传递一些查询字符串参数

试过

<Route path="/result/:type?/?filter=:filter?" exact strict component={Result}/>
Run Code Online (Sandbox Code Playgroud)

我期待捕捉像这样的网址

/result
/result/animals
/result/cars
/result/animals?filter=cats,dogs
/result/cars?filter=sedan,truck
Run Code Online (Sandbox Code Playgroud)

正确的做法是什么?

Moe*_*Moe 9

对于url 参数,例如/animalsand /cars,您可以使用冒号语法/:type

但是对于查询参数,比如?filter=something,你需要解析查询字符串。

根据反应路由器文档:

React Router 对你如何解析 URL 查询字符串没有任何意见。一些应用程序使用简单的 key=value 查询字符串,但其他应用程序在查询字符串中嵌入数组和对象。因此,由您自己解析搜索字符串。

在支持 URL API 的 现代浏览器中 ,您可以从中实例化一个URLSearchParams对象 location.search并使用它。

不支持 URL API(阅读:IE)的浏览器中, 您可以使用 3rd 方库,例如 query-string

例如,在您的组件中,您将拥有location来自父级的道具Route(或者您可以从 中获取它withRouter),然后您可以location.search像这样解析查询字符串:

function Parent({location}) {
  let params = new URLSearchParams(location.search);

  return <Child name={params.get("filter")} />;
}
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息: