如何在 react-router v4 中解析查询字符串 [英] How to parse query string in react-router v4
问题描述
在 react-router v3 中,我可以使用 props.location.query.foo
访问它(如果当前位置是 ?foo=bar
)
In react-router v3 I could access it with props.location.query.foo
(if the current location was ?foo=bar
)
在 react-router-dom@4.0.0
props.location
中只有 props.location.search
是一个像 <代码>?foo=bar&other=thing.
In react-router-dom@4.0.0
props.location
only has props.location.search
with is a string like ?foo=bar&other=thing
.
也许我需要手动解析和解构该字符串以找到 foo
或 other
的值.
Perhaps I need to manually parse and deconstruct that string to find the value for foo
or other
.
console.log(this.props)
的截图:(注意如何从 ?artist=band
此处我想从 artist
获取值,即值 band
)
Screenshot of console.log(this.props)
:
(Note how from ?artist=band
here I'd like to get the value from artist
which is the value band
)
推荐答案
看起来你已经假设正确了.解析查询字符串的能力已从 V4 中移除,因为多年来一直有请求支持不同的实现.有了这个,团队决定最好由用户决定实现的样子.我们建议导入查询字符串库.你提到的 到目前为止对我来说效果很好.
Looks like you already assumed correct. 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. The one you mentioned has worked great for me so far.
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 search = props.location.search; // could be '?foo=bar'
const params = new URLSearchParams(search);
const foo = params.get('foo'); // bar
您可以在此处
这篇关于如何在 react-router v4 中解析查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!