反应路由器中的查询字符串

Querystring in react-router

我正在尝试使用查询字符串设置路由路径。内容如下:

www.mywebsite.com/results?query1=:query1&query2=:query2&query3=:query3

我会像这样过渡到 "Results" 组件:

<Route path="/" component={Main}>
  <IndexRoute component={Home} />
  <Route path="results?query1=:query1&query2=:query2&query3=:query3"
    component={SearchResults} />
</Route>

在 SearchResults 容器中,我希望能够访问 query1、query2 和 query3 参数。

我无法让它工作。我收到以下错误:

bundle.js:22627 Warning: [react-router] Location "/results?query1=1&query2=2&query3=3" did not match any routes

我尝试按照以下指南中的步骤操作:(部分:查询字符串参数如何?) https://www.themarketingtechnologist.co/react-router-an-introduction/

我可以得到一些帮助吗?

如果您使用的是 React Router v2.xx,您可以通过传递给 Route 组件的 location.query 对象访问查询参数。

换句话说,您可以将路线修改为如下所示:

<Route path="results" component={SearchResults} />

然后在 SearchResults 组件中,使用 this.props.location.query.query1(类似于 query2query3)访问查询参数值。

编辑: React Router 仍然如此 v3.xx。

如果您使用的是 React Router >= v4 location.query 不再可用。你可以插入一个外部库(比如 https://www.npmjs.com/package/query-string),或者使用这样的东西:

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

(请记住,Internet Explorer 不支持 URLSearchParams()