我当前的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?
答案 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 }
}}
/>
)
}
/>
)
}