从反应路由器哈希段获取查询参数

我正在使用react和react-router作为客户端的应用程序。 我似乎无法弄清楚如何从像这样的url获取以下查询参数:

http://xmen.database/search#/?status=APPROVED&page=1&limit=20 

我的路线看起来像这样(我知道path是完全错误的):

 var routes = ( <Route> <DefaultRoute handler={SearchDisplay}/> <Route name="search" path="?status=:status&page=:page&limit=:limit" handler={SearchDisplay}/> <Route name="xmen" path="candidate/:accountId" handler={XmenDisplay}/> </Route> ); 

我的路线工作正常,但我不知道如何格式化path来获取我想要的参数。 感谢任何帮助!

注意:从评论复制/粘贴。 一定要喜欢原来的post!

写入es6和使用反应0.14.6 / react-router 2.0.0-rc5。 我使用这个命令查询我的组件中的查询参数:

 this.props.location.query 

它在url中创build一个所有可用查询参数的散列。

OLD(pre v4):

写入es6和使用反应0.14.6 / react-router 2.0.0-rc5。 我使用这个命令查询我的组件中的查询参数:

 this.props.location.query 

它在url中创build一个所有可用查询参数的散列。

更新(反应路由器v4 +):

React Router 4中的this.props.location.query已被删除(目前使用v4.1.1)更多关于这个问题: https : //github.com/ReactTraining/react-router/issues/4410

看起来他们希望你使用自己的方法来parsing查询参数,目前使用这个库来填补空白: https : //github.com/sindresorhus/query-string

以上答案在react-router v4不起作用。 这是我做了什么来解决这个问题 –

首先安装parsing所需的查询string 。

npm install -save query-string

现在在路由组件中,您可以像这样访问未parsing的查询string

this.props.location.search

您可以通过login控制台来进行交叉检查。

最后parsing来访问查询参数

 const queryString = require('query-string'); var parsed = queryString.parse(this.props.location.search); console.log(parsed.param); // replace param with your own 

所以如果查询是像?hello=world

console.log(parsed.hello)会loggingworld

"react-router": "^2.4.1"

url如http://localhost:8080/react-router01/1?name=novaline&age=26

const queryParams = this.props.location.query;

queryParams是一个包含查询参数的对象: {name: novaline, age: 26}

在阅读其他答案之后(首先由@ duncan-finney,然后由@Marrs),我着手寻找解释这种习惯反应路由器2.x方法的更改日志。 在组件中使用位置 (您需要查询)的文档实际上与实际的代码相矛盾。 所以如果你听从他们的意见,你会得到如此大的愤怒警告:

 Warning: [react-router] `context.location` is deprecated, please use a route component's `props.location` instead. 

事实certificate,你不能有一个叫做位置的上下文属性使用位置types。 但是,您可以使用使用位置types的称为loc的上下文属性。 所以解决方法是对它们的来源进行一些小修改,如下所示:

 const RouteComponent = React.createClass({ childContextTypes: { loc: PropTypes.location }, getChildContext() { return { location: this.props.location } } }); const ChildComponent = React.createClass({ contextTypes: { loc: PropTypes.location }, render() { console.log(this.context.loc); return(<div>this.context.loc.query</div>); } }); 

你也可以只传递你想要在你的孩子中的位置对象的部分获得同样的好处。 它没有改变警告改变为对象types。 希望有所帮助。