我只是无法让react-router加载嵌套页面。
我有React-Router的以下配置
import React from 'react';
import { Router, Route, IndexRoute, useRouterHistory } from 'react-router';
import { createHistory } from 'history';
import App from './components/app';
import Authors from'./components/authors/authorPage';
import About from'./components/about/aboutPage';
const appHistory = useRouterHistory(createHistory)({ basename: "/" });
const Routes = () =>
{
const routes = (
<Route path="/" component={App}>
<Route path="/about" component={About}/>
<Route path="/authors" component={Authors}/>
</Route>
);
return (
<Router history={ appHistory }>
{routes}
</Router>);
};
export default Routes;
它通过标题页中的链接调用
import React from 'react';
import { Router, Route, Link } from 'react-router';
const Header = () =>
{
return (
<nav className="navbar navbar-default">
<div className="container-fluid">
<a href="/" className="navbar-brand">
<img src="images/pluralsight-logo.png"/>
</a>
<ul className="nav navbar-nav">
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/authors">Authors</Link></li>
</ul>
</div>
</nav>
);
};
export default Header;
应用程序组件
import Home from './homePage';
import Header from './common/header';
const App = () =>
{
return (
<div>
<Header />
<div className="container-fluid">
<Home/>
</div>
</div>
);
};
export default App;
根应用程序加载得很好,我看到主根页面。但是,单击任何链接只会将地址栏更改为该链接(http://localhost:9005/about
),但没有任何渲染,约会页面永远不会加载。
事实上,如果我手动输入该页面(http://localhost:9005/about
),我会收到错误
Cannot GET /about
答案 0 :(得分:1)
您在预期要加载路线的地方错过children
。
const App = ({ children }) =>
{
return (
<div>
<Header />
<div className="container-fluid">
<Home/>
{children} <--- Route components will appear here
</div>
</div>
);
};
据推测,您不希望同时显示Home
以及其他网页,因此请使用IndexRoute
更新您的路线配置,以便Home
上显示<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/about" component={About}/>
<Route path="/authors" component={Authors}/>
</Route>
根网址。
example.com/username