2017-09-20 27 views
1

我注意到,如果我創建<Route path={'/'} exact component={Profile} />,我不能嵌套任何其他內部組件,只是因爲該「prop」支持阻止任何匹配並停止呈現。React-router v4。 「精確」的道具是否禁止嵌套路線?

我試圖建立的是一個簡單的應用程序與配置文件和訂單頁面。每個頁面都有自己的側邊欄和一些訂購商品列表。根據當前位置,我在每個頁面內部使用嵌套路線重新輸入正確的順序列表。爲了使這個應用程序完美,我需要在起始位置渲染配置文件頁面(例如'https://myapp.com')。

我閱讀所有文檔,唯一的解決方案是在Route組件中使用「精確」的道具。但這是太脆弱的解決方案,因爲如果我想使用嵌套路線進行側欄或訂單清單定義。

是否有任何其他方式建立一個路由,可以顯示'https://myapp.com'位置的配置文件頁面,但也允許我使用嵌套路由?

我目前的實現是未來:

<Switch> 
    <Route path={'/'} exact component={Profile} /> 
    <Route path={'/orders'} component={Orders} /> 
    <Route component={NotFound} /> 
</Switch> 

class Profile extends Component { 
    render() { 
     return (
     <div className='profile_page'> 
      <Profile_Bar /> 

      <div className='content'> 
       <Switch> 
        <Route path={'/subscribers'} component={User_List} /> 
        <Route path={'/dashboard'} component={Dashboard} /> 
       </Switch> 
      </div> 
     </div> 
    ) 
    } 
} 

class Orders extends Component { 
    render() { 
     return (
     <div className='orders_page'> 
      <Orders_Bar /> 

      <div className='content'> 
       <Switch> 
        <Route path={'/active'} component={Orders_List} /> 
        <Route path={'/completed'} component={Orders_List} /> 
       </Switch> 
      </div> 
     </div> 
    ) 
    } 
} 

const NotFound = ({ location }) => (
    <div> 
    NotFound {location.pathname} 
    </div> 
) 

在我的舊實現我使用<Redirect />代替:

<Switch> 
    <Redirect from='/' to='/profile'/> 
    <Route path={'/profile'} component={Profile} /> 
    <Route path={'/orders'} component={Orders} /> 
    <Route component={NotFound} /> 
</Switch> 
+0

您能顯示路線的完整代碼嗎?另外,你是什麼意思的'嵌套路線'? –

+0

謝謝你。我已經完成了這個 –

回答

3

理想的情況下你檔案組件將在像「/型材自己的路由處理'並創建一個單獨的組件,說首頁,爲您的'/'路線:

<Switch> 
    <Route path={'/'} exact component={Home} /> 
    <Route path={'/profile'} component={Profile} /> 
    <Route path={'/orders'} component={Orders} /> 
    <Route component={NotFound} /> 
</Switch> 

...然後你檔案組件必須分路線是這樣的:

<Switch> 
    <Route path={'/profile/subscribers'} component={User_List} /> 
    <Route path={'/profile/dashboard'} component={Dashboard} /> 
</Switch> 

如果你真的不想在路由路徑中的「配置文件」,那麼你可以將'/ subscribers'和'/ dashboard'路線添加到您的主要路線,這兩個路線都會渲染配置文件組件,但您可能仍然希望使用其自己的組件處理「/」路線:

<Switch> 
    <Route path={'/'} exact component={Home} /> 
    <Route path={'/subscribers'} component={Profile} /> 
    <Route path={'/dashboard'} component={Profile} /> 
    <Route path={'/orders'} component={Orders} /> 
    <Route component={NotFound} /> 
</Switch> 

我想另一個選擇是改變你的路線的順序,以便'/ orders'在'/'之前匹配。然後,您可以從'/'路線刪除確切,以便子路線也匹配。

在這種情況下,雖然,你將不得不處理在檔案組件,這是不理想的NOTFOUND路線。

<Switch> 
    <Route path={'/orders'} component={Orders} /> 
    <Route path={'/'} component={Profile} /> 
</Switch> 
+0

謝謝你的答案。這是一個很好的解決方案。我會試試看 –