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

);

}

}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐