一、概述

        本文将通过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 (
        <div>
            <h1>Login Page</h1>
            <button onClick = () => dispatch(Login())>Login</button>
        </div>
    );
    
};

welcome-page.js (首页)

 const Welcome = () =>{
    const [state, dispatch] = useReducer(authReducer,intializeState)
    return (<div>
                <h1>Home Page</h1>
                {state.loggined
                    ?<button onClick =()=> {dispatch(Logout())}>LogOut</button>
                    :'请登录'}
            </div>);
}

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

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

    return (
        <ul>
            <li><Link to = '/'>Home</Link></li>
            <li><Link to = 'login'>Login</Link></li>
        <ul>
        <Router>
            <Switch>
                <Route exact path = '/' component = {Welcome} />
                <Route exact path = '/login' render = {() => {
                    state.isLoggined ? <Redirect to = '/'/>
                    :<AuthPage/> }/>
            </Switch>
        </Router>
    );
    
}
11-28 10:52