问题:
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:

回答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.