【问题标题】:React Router: Query Param Match?React Router:查询参数匹配?
【发布时间】:2018-09-18 07:55:23
【问题描述】:

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

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

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

【问题讨论】:

  • 你能提供一些代码,这样更容易看到你想做什么
  • 对不起,我在晚上放假回家时在手机上做这个。 (我不是开车的人。)我的组件也比 React 教程复杂一点,但我会尝试做一个演示。

标签: reactjs react-router react-router-v4 html5-history


【解决方案1】:

尝试使用render function prop 而不是Routecomponent 属性。像这样的:

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

【讨论】:

  • 我正在使用其他一些组件进行此操作。对于这种情况,我没有考虑。即使我这样做了,我也不会认为它会起作用,但它确实有效!
  • @AmerllicA 我不太了解你,你是在问我的答案是否真的有效吗?这个我自己没用过,你可以问问OP在他的项目中是怎么做的。
  • 这个 queryStringContains 方法是什么?你是从哪个文件导入的?反应路由器?
  • @theprogrammer 这是一些伪代码,意味着您应该将其扩展为几行来执行此函数名称所描述的操作。为了更直接,将queryStringContains('A') 替换为window.location.search.includes('A') 之类的东西
【解决方案2】:

有两种方法可以做到这一点:

1) 在 react 组件中使用 location.search 获取查询字符串,然后将其传递给子组件,以防止重新渲染整个组件。 React-router 对此有 the official example

2) 定义路由器的正则表达式路径以捕获查询字符串,然后将其传递给反应组件。以分页为例:

routes.js,路由器配置可以参考this

const routerConfig = [
  {
    path: '/foo',
    component: 'Foo',
  },
  {
    path: '/student/listing:pageNumber(\\?page=.*)?',
    component: 'Student'
  },

Student.js

  render() {
    // get the page number from react router's match params
    let currentPageNumber = 1;
    // Defensive checking, if the query param is missing, use default number.
    if (this.props.match.params.pageNumber) {
      // the match param will return the whole query string, 
      // so we can get the number from the string before using it.
      currentPageNumber = this.props.match.params.pageNumber.split('?page=').pop();
    }
    return <div> 
             student listing content ...
             <Pagination pageNumber = {currentPageNumber}> 
           </div>
  }

分页.js

render() {
    return <div> current page number is {this.props.pageNumber} </div>
  }

第二种解决方案更长但更灵活。用例之一是服务器端渲染:

除了 react 组件之外,应用程序的其余部分(例如预加载的 saga)需要知道包含查询字符串的 url 才能进行 API 调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2016-06-20
    • 2021-10-25
    • 2017-06-20
    • 1970-01-01
    相关资源
    最近更新 更多