How to render components with query strings React-Router

问题: CodeSandbox — https://codesandbox.io/s/1y9z905x2l I'm trying to render components with react-router, but I don't understand correctly how to work with query strings. So c...

问题:

CodeSandbox — https://codesandbox.io/s/1y9z905x2l

I'm trying to render components with react-router, but I don't understand correctly how to work with query strings. So condition — if ?tbm=first ⟹ it'll render first component and so on. How to do this?

Example:

enter image description here


回答1:

A different query string doesn't form a different path. In your example, the path is always the same, i.e. /search, so routing cannot differentiate between your components.

If you amend your code to have three actual paths (/first, /second and /third) and amend the links accordingly, then your code works as intended, see https://codesandbox.io/s/3xqq1r06jq

If you want to switch on the query string, you have to stick to a single Route with path /search and display your component object based on the parsed querystring, see https://codesandbox.io/s/5x64nq5xkn


回答2:

The query string will be available inside this.props.location.search inside your rendered component. So the idea is you need to have a parent component which gets rendered something like this.

<Route path="/" component={parentComponent} />

Now whatever you enter as query string will be available and you can see that if you crack open your react dev tool. And once you have this string just parse it and have dynamic routes based on your custom condition. check out image for your reference.enter image description here

  • 发表于 2019-02-14 01:00
  • 阅读 ( 185 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除