在 React Router v4 中表示 URL 查询

Representing URL Queries in React Router v4

我看过其他一些使用不同版本的 React-Router(v4 之前)的示例,但我似乎无法找到一种方法来正确表示 URL 参数。

例如,如果我想从搜索结果中向朋友发送 link,它看起来像:
https://yourwebsite.com/search?item-name=youritem

在这种情况下,我知道 React-Router(v4) 可以提供可选参数,但它们未在 URL 中表示,因此您如何能够将确切的请求发送到服务器以获取信息。

即我将上面的 link 发送给朋友 -> 它到达服务器然后数据被填充到组件中。

你真的没有什么特别的事情要做,就像这样设置一个Route:

<Route path="/search" component={MySearchComponent} />

这将设置 /search 路线。然后,要访问传递的任何查询参数,请在 MySearchComponent:

const queryParameters = this.props.location.search;

location 属性通过 React Router 传递给组件。它包含整个查询字符串。所以如果我导航到:

https://myWebsite.com/search?foo=bar&baz=buzz

那么 this.props.location.search 将是:

'?foo=bar&baz=buzz'

这类似于Location.search on modern browsers. Next, you can use a querystring parser library like the builtin querystring or any others in NPM, or even the browser's own URLSearchParams

const params = new URLSearchParams(queryParameters);
const foo = params.get('foo'); //baz
const baz = params.get('baz'); //buzz

请注意,Internet Explorer 不支持此功能。我建议改用 NPM 库。