React实现登录授权功能
一、概述
本文将通过React Router & React Redux & Umi.js useModel 实现登录和授权路由功能。
Redux实现用户认证状态流转,目前只简单实现登录和登出两个功能。
useModel实现全局数据状态管理。
React Router实现路由动态管理。
二、技术实现
authState.js(redux配置)
export const Login = (username, password) => ({type: 'login',username: username,password: password };
export const Logout = (username) => ({type: 'logout', username: username});export const AuthReducer = (state, action) =>{switch(action.type){case 'Login':const res = auth(action.username, action.password);if (res){return {...state, loggined:true, username}}return state;case 'Logout':const res = unauth(action.username);if (res){return {...state, loggined:false}}return state;}
}export const AuthInitialState = {loggined: false};
authModel.ts
const [state, dispatch] = useReducer(AuthReducer,AuthInitialState);exprot default function AuthModel(){return {state,dispatch}
}
auth-page.js (登录页)
export const AuthPage = () =>{const [state, dispatch] = useModel("userModel");return (<div><h1>Login Page</h1><button onClick = () => dispatch(Login())>Login</button></div>);};
welcome-page.js (首页)
const Welcome = () =>{const [state, dispatch] = useModel("userModel")return (<div><h1>Home Page</h1>{state.loggined?<button onClick =()=> {dispatch(Logout())}>LogOut</button>:'请登录'}</div>);
}
app.js (入口,配置路由)
const App = () => {const [state] = userModel("userModel");return (<ul><li><Link to = '/'>Home</Link></li><li><Link to = 'login'>Login</Link></li><ul><Router><Switch><Route exact path = '/' render= {() => {state.isLoggined ? <WelcomePage/>: <Redirect to = '/login'/>}} /><Route exact path = '/login' render = {() => {state.isLoggined ? <Redirect to = '/'/>:<AuthPage/> }/></Switch></Router>);}