如何在 react-router v4 中获取查询参数 [英] How to get query parameters in react-router v4
问题描述
我在我的项目中使用 react-router-dom 4.0.0-beta.6.我有如下代码:
I'm using react-router-dom 4.0.0-beta.6 in my project. I have a code like following:
<Route exact path="/home" component={HomePage}/>
我想在 HomePage
组件中获取查询参数.我找到了 location.search
参数,它看起来像这样:?key=value
,所以它是未解析的.
And I want to get query params in HomePage
component.
I've found location.search
param, which looks like this: ?key=value
, so it is unparsed.
使用 react-router v4 获取查询参数的正确方法是什么?
What is the right way to get query params with react-router v4?
推荐答案
解析查询字符串的能力已从 V4 中移除,因为多年来一直有请求支持不同的实现.有了这个,团队决定最好由用户决定实现的样子.我们建议导入查询字符串库.这是我使用的一个
The ability to parse query strings was taken out of V4 because there have been requests over the years to support different implementation. With that, the team decided it would be best for users to decide what that implementation looks like. We recommend importing a query string lib. Here's one that I use
const queryString = require('query-string');
const parsed = queryString.parse(props.location.search);
如果你想要一些原生的东西并且它适合你的需要,你也可以使用 new URLSearchParams
You can also use new URLSearchParams
if you want something native and it works for your needs
const params = new URLSearchParams(props.location.search);
const foo = params.get('foo'); // bar
您可以在此处
这篇关于如何在 react-router v4 中获取查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!