React Router 6 路由权限配置

2022-04-01T04:22:05.874Z阅读114
2

根据官方的例子来看,这里通过AuthProviderRequireAuth实现

AuthProvider

import React, { useState } from 'react'
import { setToken } from 'utils/storage'

export const AuthContext = React.createContext()

export const useAuth = () => React.useContext(AuthContext)

export function AuthProvider(props) {
  let [auth, setAuth] = useState('')
  let signin = (token, cb) => {
    if (token) {
      setToken(token)
      setAuth(token)
      return cb()
    }
  }

  let signout = (cb) => {
    setAuth('')
    cb()
  }
  const value = { auth, signin, signout }
  return (
    <AuthContext.Provider value={value}>{props.children}</AuthContext.Provider>
  )
}

RequireAuth

import { Navigate, useLocation } from 'react-router'
import { getToken } from 'utils/storage'
import { useAuth } from './AuthProvider'
export function RequireAuth({ children }) {
  let auth = useAuth()
  let location = useLocation()

  if (!auth.auth && !getToken()) {
    return <Navigate to={'/login'} stat={{ from: location }} replace></Navigate>
  }

  return children
}

路由配置

 <Router>
      <div className="App">
        <AuthProvider>
          {/* <Link to={'/login'}>登陆</Link>
        <Link to={'/home'}>首页</Link> */}
          {/* 配置路由的规则 */}
          <Routes>
            <Route path="/" element={<Navigate to={'/login'} />}></Route>
            <Route
              path="/home"
              element={
                <RequireAuth>
                  <Layout />
                </RequireAuth>
              }
            >
              <Route path="" element={<Home />}></Route>
              <Route path="list" element={<ArticleList />}></Route>
              <Route path="publish" element={<ArticlePublish />}></Route>
            </Route>
            <Route path="/login" element={<Login />}></Route>
            {/* 配置404组件 */}
            <Route path="*" element={<NotFound />}></Route>
          </Routes>
        </AuthProvider>
      </div>
    </Router>
*邮箱为选填, 若输入邮箱,您留言的回复,将在第一时间以邮件的形式通知您。
总共0条留言
No Data