2017-03-17 62 views
11

在反应路由器V3我可以props.location.query.foo访问它(如果当前位置是?foo=bar如何分析中反应路由器V4

[email protected]props.location只有props.location.search与查询字符串就像?foo=bar&other=thing一个字符串。

也许我需要手动解析并解构该字符串以找到fooother的值。

截图的console.log(this.props)enter image description here (注意是如何从这里?artist=band我想从artist这是值band得到的值)

+0

为了配合我,我会导入https://www.npmjs.com/package/query-string并手动完成。 –

回答

37

您似乎已经认为是正确的。解析查询字符串的能力已从V4中取出,因为多年来一直有请求支持不同的实现。有了这些,团队决定用户最好决定实现的样子。我们建议导入一个查询字符串库。到目前为止,one you mentioned对我来说效果很好。

const queryString = require('query-string'); 

const parsed = queryString.parse(props.location.search); 

您也可以使用new URLSearchParams如果你想要的东西本土和它适用于您的需求

const search = props.location.search; // could be '?foo=bar' 
const params = new URLSearchParams(search); 
const foo = params.get('foo'); // bar 

你可以阅读更多关于here

+1

你在哪里添加了这个,所以它在每个路线的渲染中都可用? – claya

+0

URLSearchParams在iOS和SSR上不可用。查询字符串是更稳定的解决方案。 – emil

3

很高兴我发现这个职位的决定。感谢您的链接,几个小时后,我终于升级了我的代码。

对于那些你使用查询字符串,你可能需要做一些像

var nameYouWant = queryString.parse(this.props.location.search).nameYouWant; 

这是发生在我的情况,并this.props.location.search.theUrlYouWant会拒绝工作。泰勒提到的第二个选项也为我工作了一些类似的调整。