目前我正在为我的应用程序使用以下代码。
const {
Router,
Route,
IndexRoute,
Redirect,
Link,
IndexLink,
hashHistory
} = ReactRouter
var App = React.createClass({
render : function() {
return (
<div>
<h1>My Application</h1>
<div><Link to="/levelone/1">Go to One</Link></div>
<div><Link to="/levelone/1/leveltwo/5">Go to Three</Link></div>
{this.props.children}
</div>
)
}
})
var Index = React.createClass({
render : function() {
return (
<div>
<h2>This is index route</h2>
</div>
)
}
})
var LevelOne = React.createClass({
render : function() {
return (
<div>
<h2>This is LevelOne</h2>
{this.props.children}
</div>
)
}
})
var LevelTwo = React.createClass({
render : function() {
return (
<div>
<h2>This is LevelTwo</h2>
</div>
)
}
})
var routes= (
<Route path= "/" component={App}>
<IndexRoute component={Index}/>
<Route path="/levelone/:id" component={LevelOne}>
<Route path="/leveltwo/:idd" component={LevelTwo}/>
</Route>
</Route>
)
ReactDOM.render(<Router history={ hashHistory } routes={routes}></Router>, document.getElementById('app'));
<script src="https://unpkg.com/react@15.1.0/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/react-dom@15.1.0/dist/react-dom.js"></script>
<script src="https://npmcdn.com/react-router@3.0.0/umd/ReactRouter.js" charset="utf-8"></script>
<div id="app"><div>
在上面的代码中,我从组件 App
链接到 /levelone/1/leveltwo/5
,它不工作并显示错误 [ react-router] 位置“/levelone/1/leveltwo/5”不匹配任何路由
。
但是如果我将链接放在组件 LevelOne
中,就像下面的代码片段一样,链接将指向 LevelTwo,就像我想要的那样
var LevelOne = React.createClass({
render : function() {
return (
<div>
<h2>This is LevelOne</h2>
<div><Link to="leveltwo/5">Go to LevelTwo</Link></div>
{this.props.children}
</div>
)
}
})
如果想从最外层组件链接到LevelTwo,怎么办?
最佳答案
当嵌套路由时,当您打算实际使用相对路径而不是使用绝对路径时要小心。你的路线定义
<Route path="/leveltwo/:idd" component={LevelTwo}/>
应该改为:
<Route path="leveltwo/:idd" component={LevelTwo}/>
为什么<div><Link to="leveltwo/5">Go to LevelTwo</Link></div>
的原因工作是因为<Link>
仅支持绝对路径(见上文)并且实际上指向 /leveltwo/5
并且您最初的路由定义是用绝对路径定义的。因此,尽管代码运行了,但实际上并没有按照您预期的方式运行。
关于javascript - 如何链接到 React Router 中的嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41698869/