您好,我使用的是 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
正确的做法是什么?
原文由 handsome 发布,翻译遵循 CC BY-SA 4.0 许可协议
对于 _url 参数_,例如
/animals
和/cars
,您可以使用冒号语法/:type
但是对于 _查询参数_,比如
?filter=something
,你需要解析查询字符串。根据反应路由器文档:
例如,在您的组件中,您将拥有
location
作为来自父级的道具Route
(或者您可以从withRouter
获取),然后您可以- 使用location.search
像这样解析查询字符串:欲了解更多信息:
React Router 文档 - 查询参数
示例代码沙箱