反应路由器:查询参数匹配?

try*_*sis 5 html5-history reactjs react-router react-router-v4

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

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

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

Pan*_*潘俊杰 5

尝试render函数 prop而不是componentprop of Route。像这样的东西:

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


Eri*_*Tan 5

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

1)location.search在 react 组件中使用获取查询字符串,然后将其传递给子组件以防止重新渲染整个组件。React-router 有关于这个的官方例子

2)定义router的正则表达式路径来捕获查询字符串,然后传递给react组件。以分页为例:

route.js,对于路由器配置,你可以参考这个

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

学生.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>
  }
Run Code Online (Sandbox Code Playgroud)

分页.js

render() {
    return <div> current page number is {this.props.pageNumber} </div>
  }
Run Code Online (Sandbox Code Playgroud)

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

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