我有一个PrivateRoute
组件,
interface Props {
path: string,
exact: boolean,
component: React.FC<any>;
}
const PrivateRoute: React.FC<Props> = ({ component, path, exact }) => {
return (
<Route
path={path}
exact={exact}
>
{
getCookie('name').length !== 0 ? component : <Redirect to="/login" />
}
</Route>
);
}
但是当我试图在PrivateRoute
中使用useState
钩子时,我得到了invalid hook call
错误。
例如,
const [some, setSome] = useState(true);
// Calling this inside a private route will throw an error!
如何解决这个问题?
编辑
这就是PrivateRoute
的用法,
<Switch> // from react-router-dom
<Route path="/login" component={Login} />
<PrivateRoute path="/" exact component={Home} />
</Switch>
编辑2
发布于 2021-06-13 15:56:30
这现在起作用了。
export const PrivateRoute: React.FC<{
component: React.FC<any>;
path: string;
exact: boolean;
}> = ({ component, path, exact }) => {
const auth = useAuthProvider();
return auth.isAuth ? <Route path={path} exact={exact} component={component}/> : <Redirect to="/" />
};
https://stackoverflow.com/questions/67948781
复制相似问题