反应路由器:查询参数匹配? [英] React Router: Query Param Match?

查看:36
本文介绍了反应路由器:查询参数匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个问题的公认答案, React Router 4 不再匹配查询参数.如果我从与我的 <Route> 之一匹配的 URL 转到具有不同查询字符串的相同 URL,则内容似乎没有改变.我相信这是因为在匹配相同 的 URL 之间导航不会改变内容,但如果我错了,请纠正我.鉴于此,我如何将 React Router 用于一组只需要通过查询参数来区分的 URL?

According to the accepted answer to this question, React Router 4 doesn't match query parameters anymore. If I go from a URL matched by one of my <Route>s to the same URL with a different query string, the content doesn't seem to change. I believe this is because navigating between URLs that match the same <Route> doesn't change the content, but please correct me if I'm wrong. Given this, how do I use React Router for a set of URL's that need to differ only by query parameter?

例如,许多搜索引擎和其他使用搜索栏的站点,包括我正在处理的站点,都使用查询参数,通常是qquery.用户可能搜索一件事,然后决定这不是他/她想要的,然后搜索另一件事.用户可以输入第二个 URL 或再次使用搜索栏进行搜索.URL 路径中实际上没有搜索词的位置,因此需要将其放入查询字符串中.我们如何处理这种情况?

For example, many search engines and other sites that use search bars, including the site I am working on, use a query parameter, commonly q or query. The user may search for one thing, then decide that is not what he/she wants and search for another thing. The user may type in the second URL or search with the search bar again. There isn't really a place for the search term in the URL path, so it kind of needs to go in the query string. How do we handle this situation?

有没有办法使用 React Router 链接到仅在查询字符串中不同的 URL 并更改内容,而无需刷新整个页面? 最好,这不需要任何除了 React 和 React Router 之外的外部库.

Is there a way, with React Router, to link to a URL that only differs in the query string and change the content, without refreshing the entire page? Preferably, this wouldn't require any external library besides React and React Router.

推荐答案

试试 render function prop 而不是 Routecomponent prop.像这样:

Try the render function prop instead of component prop of Route. Something like this:

<Route render={props => {
  // look for some param in the query string...
  const useComponentA = queryStringContains('A');
  if(useComponentA) {
    return <ComponentA {...props}/>;
  } else {
    return <ComponentB {...props}/>;
  }
}}/>

这篇关于反应路由器:查询参数匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆