簡體   English   中英

如何使用反應路由器將路由設為私有

[英]How to make routes private using 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);

那是因為你有

 <Route component={Error}/>

作為開關的第三項。

Switch 渲染第一個孩子或與該位置匹配的孩子。

由於您沒有指定路徑,我想它會始終匹配,並且Switch不會使用后面的部分路由。

作為一種解決方案,要么將其與您重定向的路徑一起使用,要么完全刪除。

如果您對私有路由的不同解決方案感興趣,請查看這篇文章,例如: https://tylermcginnis.com/react-router-protected-routes-authentication/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM