2017-04-26 79 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

相关问题