2017-10-20 70 views
0

我試圖擁抱路由傳播遍佈應用而不是一箇中心位置的反應路由器4哲學。爲了簡便起見,< 應用>有效地吐出在其渲染()以下:React路由器組件無法渲染自己的子項?

<BrowserRouter> 
    <Link to='/' /> 
    <Link to='/linkb' /> 
    <Switch> 
     <Route exact path='/' component={ComponentA}> 
     <Route exact path='/linkb' component={ComponentB> 
    </Switch> 
</BrowserRouter> 

... 到目前爲止好:在導航鏈接幫我路由到相應的組分A和B和我的2頁應用程序工作正常。

我遇到的問題是,在componentB內部,現在我希望它有它自己的子路由。雖然這些路線將是<App/>的'孫子',但我沒有看到爲什麼<App/>應該知道或關心它們。我建這個(周圍的內容和CSS的東西大多是拆出來的清晰度):

B組分

import React, { Component } from "react"; 
import { BrowserRouter, Switch, Route, Link } from 'react-router-dom'; 
import ComponentC from './ComponentC'; 
import ComponentD from './ComponentD'; 

export default class ComponentB extends Component { 
    constructor(props) { super(props);} 
    render() { 
    return (
     <div> 
     <div> 
      <Link to='/linkb/c' className='btn'>link C</Link> 
      <Link to='/linkb/d' className='btn'>link D</Link> 
     </div> 
     {this.props.children} 
     <Switch> 
      <Route exact path="linkb/c" component={ComponentC}/> 
      <Route exact path="linkb/d" component={ComponentD}/> 
     </Switch> 
     </div> 
    ); 
    } 
} 

當我點擊鏈接C或鏈接d,在瀏覽器欄,但沒有改變的URL更新在頁面上/新組件不會呈現。我究竟做錯了什麼?

+1

如果您嘗試了'path =「/ linkb/c」',因爲您在路由組件上指定了確切的內容。 – Win

+0

這個網址在這一點上說的是什麼? –

+0

@AlexGuerra瀏覽器中的網址正確更新,例如:http:// localhost:3000/linkb/c'。頁面本身沒有任何變化,並且新組件不被渲染。我只是注意到,頁面並沒有變成空白,但我應該更新我的Q. – yen

回答

0

行 - 所以我得到這個工作的唯一方法是停止硬編碼子組件中的路徑,並使用通過react-router傳入的路徑段。由於這些評估爲同樣的事情(我覺得)我不確定爲什麼這個解決我的問題,但它的作用:

 <Link to={`${this.props.match.path}/c`}>link c </Link> 
     <Link to={`${this.props.match.path}/d`}>link d </Link> 

這作品!不知道爲什麼!如果有人能解釋爲什麼我會接受他們的答案,而不是我的答案。

更新:似乎是一個絕對vs相對url的情況。使用props.match.path避免了這種混淆。