react全局路由钩子(路由守卫)

// store.js


import {createStore} from 'redux'

export const store = createStore(SaveTokenReducer)

// 存储token
function SaveTokenReducer(state={token:localStorage.getItem('token')||null}, action){
    switch(action.type){
        case 'save_token':
            state.token = action.token
            break;
        default:
            break;
    }
    // console.log(state)
    return state
}

// routes.js

import Index from './views/index';
import CallUs from './views/callUs';
import Login from './views/login';
import Err404 from './views/404';

export const routes = [
    {
        path: '/',
        title: '首页',
        component: Index
    },
    { 
        path: '/callus',
        title: '联系我们',
        component: CallUs,
        auth: true  //需要拦截
    },
    {
        path: '/login',
        title: '登录',
        component: Login
    },
    {
        path: '/404',
        title: '404',
        component: Err404
    }
]

// app.js


import React from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'
import { routes } from './routes'
import { store } from './store'


function App(){
    let token = store.getSate().token
    return (
        <>
            <Router>
                <Switch>
                    {
                        routes.map((item,index)=>{
                            return (
                                <Route 
                                    key={index} 
                                    exact 
                                    path={item.path}
                                    // component={item.component} 
                                    render={
                                        props=>( 
                                                !item.auth ? (<item.component {...props} />) 
                                                           : (token ? <item.component {...props} /> 
                                                           : <Redirect to={{
                                                                   pathname: '/login',
                                                                   state: { from: props.location }
                                                            }} />)
                                            ) 
                                        
                                    }
                                />
                            )
                        })
                    }
                    <Redirect to='/404' />
                </Switch>
            </Router>
        </>
    )
}

export default App

来源:https://blog.csdn.net/beichen3997/article/details/89204065

你可能感兴趣的:(react全局路由钩子(路由守卫))