【问题标题】:How to make routes private using react router如何使用反应路由器将路由设为私有
【发布时间】:2023-04-07 17:10:01
【问题描述】:

我想将一些路由设为私有以供管理员访问。 成功登录管理员可以访问路径的位置。 但是在这里我在登录时遇到问题,它正在重定向到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);

【问题讨论】:

    标签: javascript reactjs authentication react-router


    【解决方案1】:

    那是因为你有

     <Route component={Error}/>
    

    作为switch的第三项。

    Switch 渲染第一个孩子或匹配 位置。

    由于你没有指定路径,我猜它总是匹配的,Switch 不会使用后面的部分路由。

    作为一种解决方案,要么将其与重定向路径一起使用,要么完全删除。

    如果您对私有路由的不同解决方案感兴趣,请查看这篇文章,例如:https://tylermcginnis.com/react-router-protected-routes-authentication/

    【讨论】:

      猜你喜欢
      • 2020-03-04
      • 2021-01-03
      • 2018-11-05
      • 1970-01-01
      • 2020-10-22
      • 2020-08-24
      • 2022-01-11
      • 1970-01-01
      • 2017-09-17
      相关资源
      最近更新 更多