ProtectedRoutes功能。如何调用redux useSelector()

时间:2020-01-05 13:13:57

标签: reactjs react-redux react-router

我当前的AppRoutes看起来像这样。

<Switch>
    <ProtectedRoute
        exact
        path="/"
        component={Home}
    />
    <Route path="/login" component={Login} />
</Switch>

我做了一个ProtectedRoute函数

const { isAuthenticated, isAuthenticating } = useSelector(state => state.auth)

const ProtectedRoute = ({ component: Component, ...rest }) => (    
    <Route
      {...rest}
      render={props =>
        isVerifying ? (
          <Loading />
        ) : isLoggedIn ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );

在我以前将其包含在AppRoutes中之前,但是我决定移入ProtectedRoute函数以使其看起来更整洁并承担单一责任,而不是将其作为道具传递下来。

但是出现以下错误:

无效的挂钩调用。挂钩只能在主体内部使用 功能组件。

我收到错误是因为我已经在函数外部声明了该错误,并且想知道我需要将其放置在哪里,还有没有更好的方法来处理ProtectedRoutes?

1 个答案:

答案 0 :(得分:0)

您可以将其保留在ProtectedRoute组件中吗?

const ProtectedRoute = ({ component: Component, ...rest }) => {
  const { isAuthenticated, isAuthenticating } = useSelector(state => state.auth)
  return (    
    <Route
      {...rest}
      render={props =>
        isVerifying ? (
          <Loading />
        ) : isLoggedIn ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  )
}