react router 路由守卫_react-router怎么做路由守卫?

本文介绍了如何在React应用中使用`react-router-dom`实现路由守卫,确保只有经过身份验证的用户才能访问受保护的页面。通过`PrivateRoute`组件,当用户未认证时会被重定向到登录页面。
摘要由CSDN通过智能技术生成

import React from "react";

import {

BrowserRouter as Router,

Route,

Link,

Redirect,

withRouter

} from "react-router-dom";

const AuthExample = () => (

  • Public Page

  • Protected Page

);

const fakeAuth = {

isAuthenticated: false,

authenticate(cb) {

this.isAuthenticated = true;

setTimeout(cb, 100); // fake async

},

signout(cb) {

this.isAuthenticated = false;

setTimeout(cb, 100);

}

};

const AuthButton = withRouter(

({ history }) =>

fakeAuth.isAuthenticated ? (

Welcome!{" "}

onClick={() => {

fakeAuth.signout(() => history.push("/"));

}}

>

Sign out

) : (

You are not logged in.

)

);

const PrivateRoute = ({ component: Component, ...rest }) => (

{...rest}

render={props =>

fakeAuth.isAuthenticated ? (

) : (

to={{

pathname: "/login",

state: { from: props.location }

}}

/>

)

}

/>

);

const Public = () =>

Public

;

const Protected = () =>

Protected

;

class Login extends React.Component {

state = {

redirectToReferrer: false

};

login = () => {

fakeAuth.authenticate(() => {

this.setState({ redirectToReferrer: true });

});

};

render() {

const { from } = this.props.location.state || { from: { pathname: "/" } };

const { redirectToReferrer } = this.state;

if (redirectToReferrer) {

return ;

}

return (

You must log in to view the page at {from.pathname}

Log in

);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值