当前,我在我的应用程序中使用以下代码。
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/[email protected]/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://npmcdn.com/[email protected]/umd/ReactRouter.js" charset="utf-8"></script>
<div id="app"><div>
在上面的代码中,我从组件
/levelone/1/leveltwo/5
链接到App
,该组件不起作用,并显示错误[react-router] Location "/levelone/1/leveltwo/5" did not match any routes
。但是,如果我将链接放在组件
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
,并且最初使用绝对路径定义了路由定义。因此,尽管代码运行了,但实际上并没有按照您的预期运行。