React路由器4中的嵌套路由

时间:2018-01-29 07:49:26

标签: reactjs react-router-v4

我有一个组件,App组件,NewHome组件和Results组件。

我在组件App中的路线看起来像

 <Route exact path="/" component={NewHome} />
 <Route path="flights/search/roundtrip" component={Results} />

NewHome路线看起来像

<Route path="/flights" component={FlightSearch} />
<Route path="/hotels" component={HotelSearch} />

结果组件是基于类的反应组件

只有App组件得到渲染,但组件里面,我可以在反应devtools中看到null,而Ui只有App的一部分不是结果的一部分

<Route path="flights/search/roundtrip" component={Results}>
null
<Route /> 

理想情况下,它应该有效,但我无法理解我在这里做错了什么。任何指针或建议都会有所帮助。这种行为可能是什么原因

这是我在index.js文件中执行reactdom.render的代码

ReactDOM.render(
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <Route path="/" component={App} />
        {/* {routes} */}
      </ConnectedRouter>
    </Provider>,
    document.getElementById("root")
  )

注意:完整网址就是这样的

  

http://localhost:3001/flights/search/roundtrip?search_type=roundtrip&origin=BLR&destination=MAA&travel_date=2018-01-29&return_date=2018-02-13&class_type=ECONOMY&adult_count=1&child_count=0&residentof_india=true&infant_count=0&originAndDestinationSwapped=false&activeIndexMulticity=0

3 个答案:

答案 0 :(得分:0)

NewHome获得match道具。有了它,只需使用您可能需要的嵌套路由联系其URL。

NewHome组件:

render() {
  const { match } = this.props

  return (
    <div>
      <Route path={`${match.url}/flights`} component={FlightSearch} />
      <Route path={`${match.url}/hotels`} component={HotelSearch} />
    </div>
  )
}

答案 1 :(得分:0)

我认为是因为你遗漏了路线中的'/'。

尝试

  <Route path="/flights/search/roundtrip" component={Results} />

而不是

   <Route path="flights/search/roundtrip" component={Results} />

尝试在将组件包装到withRouter HOC

后导出组件
import { withRouter} from 'react-router-dom';

并按如下方式导出组件

export default withRouter(Results);

答案 2 :(得分:-1)

我发现了这个问题,在我的应用程序中我从react-router-dom导入Route。它可用于react-router。可能是一个正确的错误消息会帮助:)感谢@sujit和@mersocarlin提供有价值的输入。