2017-04-26 77 views
0

我使用的反應路由器V4如何從沒有結尾的斜線路由到子目錄?

假設我在以下位置

http://localhost:3000/articles 

我想這個位置有一個反應的路由器鏈接元素,它指向

http://localhost:3000/articles/new 

第一次嘗試:

<Link to="new" /> 

http://localhost:3000/new 

第二次嘗試:

<Link to="/new" /> 

從任何位置點

http://localhost:3000/new 

第三次嘗試:

<Link to="new" /> 

http://localhost:3000/articles/ /* notice the slash at the end */ 

http://localhost:3000/articles/new 

成功,但我需要它的工作範圍:

http://localhost:3000/articles 
+0

你能張貼你的路線文件嗎? –

+0

不好意思,但路由是分佈在幾個文件之間,所以這將是太多的代碼 – henk

回答

0

您應該指向的Link/articles/new

<Link to="/articles/new" />

您路由器應該與此類似:

const App =() => (
    <Router> 
    <div className="wrapper"> 
     <Route path="/" exact component={Home} /> 
     <Route path="/articles" component={Articles} /> 
     <Route path="/articles/new" component={New} /> 
    </div> 
    </Router> 
); 

注:配置你的路由器作爲例子將呈現兩種成分(文章和新建)。如果您只想修改New,則應該將屬性exact添加到父組件。

<Route path="/articles" exact component={Articles} />

+0

這個解決方案的問題是當我有像「userID/articles/new」我需要管理userID和創建路線。所以我希望有一個更簡單的方法來做到這一點...... – henk

+0

因此,您可以使用':'直接在您的路線上使用參數。 所以'userID/articles/new'應該是''userID/articles/new''類似的東西 你可以在[react-router-tutorial](https:// github。com/reactjs/react-router-tutorial/tree/master/lessons/06-params) –

+0

我最終得到了類似這樣的結果,每當用戶改變時,我都採用整個路徑並設置路由。但似乎這不是最優雅的方式...... – henk

相關問題