react封装鉴权路由组件以及登录时跳转到未登录时游览页面

以下代码包含了typescript的类型声明,看不懂的可以忽略这些类型声明

react封装鉴权路由组件

创建组件AuthRoute.tsx 

// hasToken 判断是否有token
import { hasToken } from '@/utils/storage'
import { Route, Redirect, RouteProps } from 'react-router-dom'

export const AuthRoute = ({ children, ...rest }: RouteProps) => {
  return (
    <Route
      {...rest}
      render={props => {
        if (hasToken()) {
           // children 与vue中插槽类似是Route包裹的内容
          return children
        }
        return (
          <Redirect
            to={{
              pathname: '/login',
              state: {
                // 传入当前游览页面的路径
                from: props.location.pathname
              }
            }}
          />
        )
      }}
    />
  )
}

在需要使用鉴别token页面使用 例App.txs

将route改成AuthRoute 

import { AuthRoute } from './components/AuthRoute'

const App = () => {
  return (
    // ...
    <AuthRoute path="/profile/edit">
      <ProfileEdit />
    </AuthRoute>
  )
}

登录时跳转到未登录时游览页面 

因为token拦截回跳转页 所以登录后需要跳回 以下是我的思路

react封装鉴权路由组件以及登录时跳转到未登录时游览页面

在登录页中 进行处理

pages/Login/index.tsx 中:

import { useLocation } from 'react-router-dom'

const Login = () => {
  // 注意: state 可能是不存在的,所以,类型中要明确包含不存在的情况,即 undefined
  const location = useLocation<{ from: string } | undefined>()

  const onFinish = async (values: LoginForm) => {
    // ...
    Toast.show({
      afterClose: () => {
        if (location.state) {
          return history.replace(location.state.from)
        }

        history.replace('/home/index')
      }
    })
  }
}

上一篇:获取企业微信授权code


下一篇:JS # hash