privateRoute.js 1.06 KB
Newer Older
zhanghaozhe committed
1 2 3 4 5
import React, { useState, useEffect } from "react"
import { Route } from "react-router-dom"
import { connect } from "react-redux"
import RouteMiddlePage from "./route-middle-page"
import Loading from "src/common/Loading"
6

zhanghaozhe committed
7
const PrivateRoute = ({ component: Component, path, user, ...rest }) => {
zhanghaozhe committed
8 9
  const [isLoading, setLoadingState] = useState(true)
  const [authenticated, setAuthorization] = useState(false)
zhanghaozhe committed
10

zhanghaozhe committed
11
  useEffect(() => {
zhanghaozhe committed
12
    let _auth = !user.hasError && user.code !== 4040
zhanghaozhe committed
13
    // eslint-disable-next-line no-unused-expressions
zhanghaozhe committed
14 15
    typeof _auth !== "undefined" &&
      (setAuthorization(_auth), setLoadingState(false))
zhanghaozhe committed
16
  }, [user.hasError, user.code])
zhanghaozhe committed
17

zhanghaozhe committed
18
  return (
zhanghaozhe committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32
    <Route
      {...rest}
      render={(props) => {
        return (
          <Loading isLoading={isLoading}>
            {authenticated ? (
              <Component {...props} />
            ) : (
              <RouteMiddlePage state={{ from: props.location }} />
            )}
          </Loading>
        )
      }}
    />
zhanghaozhe committed
33
  )
zhanghaozhe committed
34
}
35

zhanghaozhe committed
36
export default connect((state) => ({ user: state.user }), null)(PrivateRoute)