具有私有路由的React Router呈现空白页

时间:2019-03-03 21:08:23

标签: javascript reactjs

已阅读所有相关主题,但仍未找到答案

大家好,

我的代码中有一个错误,一如既往我找不到它,所以请帮助我找到使它起作用的方法。

我在创建create-react-app时尝试添加用户身份验证。我正在寻找的教程:http://jasonwatmore.com/post/2018/09/11/react-basic-http-authentication-tutorial-example

问题:登录后,我看到“仪表板”(精确)组件,一切正常。但是然后我单击其他链接,例如“订单”等。我正在呈现空白页面。控制台上没有错误。

让我们从头开始。

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import { configureFakeBackend } from './_helpers/fake-backend';
configureFakeBackend();

ReactDOM.render((
      <App />
), document.getElementById('root')); 

App.js文件

import React, { Component } from 'react';
import './App.scss';
import MainContent from './components/MainContent.jsx';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { PrivateRoute } from './components/PrivateRoute';
import { LoginPage } from './LoginPage/LoginPage';


class App extends Component {
  render() {
    return (
            <Router>
              <Switch>
                <PrivateRoute exact path="/" component={MainContent} />
                <Route path="/login" component={LoginPage} />
              </Switch>
            </Router>
    );
  }
}

export default App;

PrivateRoute.jsx

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

export const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
        localStorage.getItem('user')
            ? <Component {...props} />
            : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
    )} />
)

MainContent.jsx

import React, { Component } from 'react';
import Sidebar from './Sidebar.jsx';
import Header from './Header.jsx';
import Main from './Main.jsx';
import { userService } from '../_services/user.service';
import { Link } from 'react-router-dom';

class MainContent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            user: {},
            users: []
        };
    }
    componentDidMount() {
        this.setState({ 
            user: JSON.parse(localStorage.getItem('user')),
            users: { loading: true }
        });
        userService.getAll().then(users => this.setState({ users }));
    }
  render() {
    const { user, users } = this.state;
    return (

      <React.Fragment>
      <h1>Hi {user.firstName}!</h1>
      {users.loading && <em>Loading users...</em>}
      {users.length &&
          <ul>
              {users.map((user, index) =>
                  <li key={user.id}>
                      {user.firstName + ' ' + user.lastName}
                  </li>
              )}
          </ul>
      }
      <p>
          <Link to="/login">Logout</Link>
      </p>
        <Sidebar />
        <div id="flexing">
            <Header />
            <Main />
          </div>
      </React.Fragment>
    );
  }
}

export default MainContent;

至少: Main.jsx

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Dashboard from './Dashboard';
import Orders from './Orders';
import Routes from './Routes';
import Drivers from './Drivers';
import Settings from './Settings';

const Main = () => (
  <main>
    <Switch>
      <Route exact path='/' component={Dashboard}/>
      <Route path='/orders' component={Orders}/>
      <Route path='/routes' component={Routes}/>
      <Route path='/drivers' component={Drivers}/>
      <Route path='/settings' component={Settings}/>
    </Switch>
  </main>
);

export default Main;

因此Dashboard组件将呈现良好的效果,而其他组件则呈现空白页面的效果。请帮助修复它。等待回复。

Justas

1 个答案:

答案 0 :(得分:1)

正确的是,发生的事情是Main.js中的那些路由仅在App.js呈现时才呈现。也就是说,当路径为/时,将呈现Main.js。当出现其他情况时,Main.js不会被渲染,因此Switch组件永远不会被命中。

要解决此问题,您应该删除Main.js并将所有这些路由置于顶层(如果有帮助,您可以在App.js中拥有两个Switch组件),或者在App中设置路径.js(用于MainComponent)以包括所有这些。前者更清洁,因为后者可能变得复杂。

要查看这是问题所在,请向App.js添加默认路由,您会看到看到的“空白”页面是因为该级别上没有任何内容匹配;要设置默认值,请在*上设置路径匹配。