react-router:查询参数匹配?

IT技术 reactjs react-router react-router-v4 html5-history
2021-05-02 06:11:11

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

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

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

2个回答

尝试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}/>;
  }
}}/>

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

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

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

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

const routerConfig = [
  {
    path: '/foo',
    component: 'Foo',
  },
  {
    path: '/student/listing:pageNumber(\\?page=.*)?',
    component: '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 调用。