如何使用反应路由器将路由设为私有

时间:2020-04-15 13:14:50

标签: javascript reactjs authentication react-router

我想将某些路由设为私有以供管理员访问。 成功登录后,管理员可以访问路径。 但是这里我在登录时遇到问题,它正在重定向到error page

我还需要在此处进行其他操作来将此路线设为私有吗? 任何建议。预先感谢。

// main.js

import React, { Component } from 'react';
import {Switch, Route} from 'react-router-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Homepage from './user/Homepage';
import Aboutme from './user/AboutMe';
import Error from './user/Error';
import Dashboard from './admin/Dashboard';

class Main extends Component {
    static propTypes = {
        auth: PropTypes.object.isRequired
    }


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

        return(
            <Switch>
            <Route  exact path="/" component={Homepage}/>
            <Route path="/about" component={Aboutme}/>
            <Route component={Error}/>
            { user ? (user.is_admin === true && isAuthenticated ? 
           ( <Route path="/dashboard" component={Dashboard}/> ) : ( <Route component={Error}/>) ):  <Route component={Error}/> }

            </Switch>

        )
    }

}

const mapStateToProps = state => ({
auth: state.auth
});

export default connect(mapStateToProps, null)(Main);

1 个答案:

答案 0 :(得分:1)

那是因为你有

 <Route component={Error}/>

作为开关的第三项。

Switch呈现第一个孩子或与之匹配的孩子 位置。

由于您没有指定路径,所以我想它将始终匹配,并且Switch将不会使用后面的零件路径。

作为解决方案,可以将其与重定向路径一起使用,或者完全删除。

如果您对私人路线的其他解决方案感兴趣,请查看此文章,例如:https://tylermcginnis.com/react-router-protected-routes-authentication/