React PrivateRouter实现无法正常运行

时间:2018-06-26 21:28:41

标签: javascript reactjs react-router

我有一个具有用户登录名的小型react应用,我想拥有一条将受到保护的私有路由,并且只有经过身份验证的用户才能使用它。 这是我的代码。

App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

// Styling
import './App.css';

// Privat route
import PrivateRoute from './routes/PrivateRoute';

// Common
import Navigation from './components/common/Navigation';

// Components
import Layout from './components/Layout'
import Login from './components/Login';
import Home from './components/Home';
import Profile from './components/Profile';

export default () => (
 <Router>
    <Switch>
        <Layout>
            {/* Public routes */}
            <Route exact path="/" component={ Home } />
            <Route exact path="/login" component={ Login } />

            {/* Private routes */}
            <PrivateRoute exact path="/profile" component={ Profile } />
        </Layout>
    </Switch>
  </Router>
);

PrivateRoute.js

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

import UserService from '../services/User';

export default class PrivateRoute extends React.Component {
    state = {
      isAuthenticated: null,
      user: null
    }

    async componentDidMount(){
      let isAuthenticated, user = null;

      try{
        user = await UserService.auth();
        isAuthenticated = true;
      }catch(e){
        isAuthenticated = false;
      }
      this.setState({ isAuthenticated, user });
    }

    render() {
      const { isAuthenticated, user } = this.state;

      if(isAuthenticated === null){
        return null;
      }

      return (
          isAuthenticated ? 
            <Route path={this.props.path} component={this.props.component}/> :
            <Redirect to={{ pathname: '/login', state: { from: this.props.location }}} /> 
         );
    }
}

Home.js

import React, { Component } from 'react';

export default class Home extends Component{
    render(){
        return (
            <div>Home!</div>
        );
    }
}

我不断收到错误消息  Warning: You tried to redirect to the same route you're currently on: "/login" 即使我在主页上,也没有业务检查用户是否已通过身份验证。

我怀疑这个问题与我的路线和我要实现的通用布局有关,但是我找不到问题。

0 个答案:

没有答案