【问题标题】:React Router Conditional Route反应路由器条件路由
【发布时间】:2018-03-01 07:34:17
【问题描述】:

这是我运行良好的路线配置。

<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 -> 城市,

example.com/england -> 国家

我现在该如何设置路线?

【问题讨论】:

  • 添加了一个示例工作演示。请检查更新

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


【解决方案1】:

我建议你有一个组件路由,它将根据路由参数决定要渲染哪个组件。

<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

【讨论】:

  • 似乎这样可行。但是有什么缺点吗?喜欢历史堆栈或其他与性能相关的问题?
  • 我同意这可能会导致一些性能缺陷,仅在您尝试在 componentDidMount() fn 中操作状态的情况下。但除此之外,我没有看到任何缺点。在文档中没有提到在 componentDidMount() fn 中设置状态是不好的做法。但他们肯定提到了一些额外的渲染。 reactjs.org/docs/react-component.html#componentdidmount
  • 在您的情况下,我认为 componentDidMount() fn 是唯一适合添加逻辑以处理路由参数的地方。其他我看不出有什么缺点
  • 这很好用,但现在对 SEO 来说真的很糟糕。它现在只是服务器渲染路由页面..
猜你喜欢
  • 2021-09-28
  • 2019-04-25
  • 2017-12-06
  • 2020-06-27
  • 2017-09-16
  • 2019-02-18
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
相关资源
最近更新 更多