反应路由器条件路由

时间:2018-03-01 07:34:17

标签: reactjs react-router react-redux react-router-v4

这是我的Route配置,运行良好。

<Route path="/" component={App}>
  <IndexRoute component={Home}/>
  <Route path="city">
    <Route path=":city" component={City} />
  </Route>
  <Route path="country">
    <Route path=":country" component={Country} />
  </Route>
</Route>

适用于网址example.com/city/london和example.com/country/england

现在我想更改它,以便在用户输入

example.com/london - &gt;市

example.com/england - &gt;国家

我现在如何设置路线?

1 个答案:

答案 0 :(得分:2)

我建议您有一个组件路径,它将根据路径参数决定要渲染的组件。

<Route path="/" component={App}>
 ...
 <Route path=":place" component={CommonRoute} />
 ...
</Route>

CommonRoute组件中,您需要一些逻辑来确定param是城市还是国家。

...
componentDidMount() {
    let param = this.props.match.params.place;
    ...
    //Logic to decide what place is. i.e (city or country)
    //set the store state accordingly
    ...
}
...

render() {
  return(
    ...
    this.props.reducerName.isCity && </City>
    this.props.reducerName.isCountry && </Country>
    ...
  )
}  

嗯,这只是一个想法。如果这些有效,我建议你尝试让我们知道。希望这会有所帮助。

更新:你走了。 Working Demo

相关问题