【问题标题】:React-router not able to load nested pagesReact-router 无法加载嵌套页面
【发布时间】:2016-09-16 18:17:25
【问题描述】:

我只是无法让 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

【问题讨论】:

  • 听起来您的服务器路由设置不正确。

标签: reactjs react-router


【解决方案1】:

您在期望路由加载的位置缺少children

const App = ({ children }) =>
{
    return (
        <div>
            <Header />
            <div className="container-fluid">
                <Home/>

                {children} <--- Route components will appear here
            </div>
        </div>
    );
};

大概你不想同时显示Home 和其他页面,所以用IndexRoute 更新你的路由配置,这样Home 就会出现在根URL 上。

<Route path="/" component={App}>
    <IndexRoute component={Home}/>
    <Route path="/about" component={About}/>
    <Route path="/authors" component={Authors}/>
</Route>

【讨论】:

  • 太棒了!谢谢。修改App获取props,然后设置{props.Children},同时设置IndexRoute解决了这个问题!
  • 啊,是的,在我的回答中错过了这一点。我更新了它(如果你想使用解构,你可以删除props
猜你喜欢
  • 2020-03-26
  • 2022-01-14
  • 2017-03-18
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 2022-09-23
  • 2018-12-10
相关资源
最近更新 更多