1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| import React from "react"; import { BrowserRouter as Router, Route, Link, Redirect, withRouter } from "react-router-dom";
//////////////////////////////////////////////////////////// // 1. Click the public page // 2. Click the protected page // 3. Log in // 4. Click the back button, note the URL each time
function AuthExample() { return ( <Router> <div> <AuthButton /> <ul> <li> <Link to="/public">Public Page</Link> </li> <li> <Link to="/protected">Protected Page</Link> </li> </ul> <Route path="/public" component={Public} /> <Route path="/login" component={Login} /> <PrivateRoute path="/protected" component={Protected} /> </div> </Router> ); }
// 保存着是否登录状态 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 ? ( <p> Welcome!{" "} <button onClick={() => { fakeAuth.signout(() => history.push("/")); }}>登出</button> </p> ) : ( <p>你没有登录.</p> ) );
// 拿到传给 PrivateRoute 的 Protected 组件 和 Protected 属性,然后把传进来的属性和组件传给Route组件,Route组件返回前进行判断,如果已经登录而返回原组件,则否则生定向到login页面 function PrivateRoute({ component: Protected, ...rest }) { return ( <Route {...rest} render={props => (fakeAuth.isAuthenticated ? ( <Protected {...props} /> ) : ( <Redirect to={{ pathname: "/login", state: { from: props.location } }} /> ) ) } /> ); }
// Public 组件 function Public() { return <h3>公开的</h3>; }
// Protected 组件 function Protected() { return <h3>受保护的</h3>; }
// 登录组件 class Login extends React.Component { state = { redirectToReferrer: false };
// 更改 fakeAuth 里的状态,即登录 login = () => { fakeAuth.authenticate(() => { this.setState({ redirectToReferrer: true }); }); };
render() { debugger let { from } = this.props.location.state || { from: { pathname: "/" } }; let { redirectToReferrer } = this.state; // 如果用户已经登录则重定向到之前的页面 if (redirectToReferrer) return <Redirect to={from} />;
return ( <div> <p>您必须登录才能查看该页面 {from.pathname}</p> <button onClick={this.login}>登入</button> </div> ); } }
export default AuthExample;
|