React Router & React Reducer Hook 实现路由管理

一、概述

        本文将通过React Router & React Redux实现登录和授权路由功能,将会从以下三个部分入手。

二、技术实现

auth-action-reducer (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 initialState = {loggined: false};

auth-page.js (登录页)

export const AuthPage = () =>{
    const [state, dispatch] = useReducer(authReducer, initialState);
    
    return (
        

Login Page

); };

welcome-page.js (首页)

 const Welcome = () =>{
    const [state, dispatch] = useReducer(authReducer,intializeState)
    return (

Home Page

{state.loggined ? :'请登录'}
); }

app.js (入口,配置路由)

const App = () => {
    
    const [state] = useReducer(authReducer, initialState);

    return (
        
  • Home
  • Login
    • { state.isLoggined ? : }/> ); }

你可能感兴趣的:(前端-React,react.js)