如何在反应路线中访问获取参数

时间:2019-06-24 08:36:37

标签: reactjs react-router

我尝试以结构化的方式在我的React App的URL中获取参数。我有名为id1和id2的参数,可以像这样

看到它们
console.log("this.props.location.search", this.props.location.search)

带有参数的URL将像这样链接

<a href="compare/?id1=6bf45ef0-962e-11e9-923e-972a9f2b848f&amp;id2=58e82e60-961d-11e9-ae32-47571549c9a2">
    <button class="ui yellow button">
       Comparison
    </button>
</a>

我找到了

之类的解决方案
this.props.location.query.id1

this.props.match.params

但是this.props.match.params为空,并且this.props.location.query不存在

此外,我还测试了路线中的一些设置。但是以下内容使整个应用崩溃,只是显示一个空白屏幕

      <Route exact path="/compare(/:id1)(/:id2)" component={Compare} />

如果我这样做

      <Route exact path="/compare/:id1?/:id2?" component={Compare} />

应用再次运行,显示参数未定义

match:
  isExact: true
  params:
    id1: undefined
    id2: undefined

1 个答案:

答案 0 :(得分:1)

我认为问题在于您正在将url参数与查询字符串混合在一起。

在您的href中,您应该具有以下内容:

<a href="compare/6bf45ef0-962e-11e9-923e-972a9f2b848f/58e82e60-961d-11e9-ae32-47571549c9a2">
  <button class="ui yellow button">
      Comparison
  </button>
</a>

您的路线将如下所示:

<Route exact path="/compare/:id1/:id2" component={Compare} />

Compare组件中,您将可以使用this.props.match.params.id1this.props.match.params.id2访问参数,并向服务器发出将与查询字符串进行比较的请求。

尝试一下,让我知道是否有帮助。