如何使用React-Router从URL获取键值对

时间:2016-05-22 02:01:38

标签: reactjs react-router reactive-programming

当我们在URL中只有一个参数时反应路由器很棒但是当URL中有多个参数时,它会变得笨拙!例如, 如果网址为http://localhost:8080/foo=bar,那么我可以fooValue = bar;但如果网址为http://localhost:8080/foo=bar&this=that,那么我会得到fooValue: "bar&this=that" ...!我在这里想念的是什么?!

var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var Main = require('./templates/main.jsx');
var Child = require('./templates/child.jsx');

module.exports = {
  path: '/',
  component: Main,
  indexRoute: { component: Main },
  childRoutes: [
    {
        path: '/foo=:fooValue',
        component: child,
        onEnter: function (nextState) {
            console.log(nextState.params);
            //// OUTPUTS: {fooValue : "bar"}
        },
    },

    {
        path: '/foo=:fooValue&this=:thisValue',
        component: child,
        onEnter: function (nextState) {
            console.log(nextState.params);
            //// OUTPUTS: {fooValue: "bar&this=that"}

        },
    },

有没有办法获得键/值{fooValue : "bar", thisValue : "that"}

1 个答案:

答案 0 :(得分:0)

您不应在路径模式中设置查询参数。它们由路由器作为location属性传递给组件,只需通过以下方式访问它们:

 let { query } = this.props.location
 console.log(query);

看看this example