【发布时间】:2021-08-29 02:13:11
【问题描述】:
我有一个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
【问题讨论】:
-
在应用程序中如何使用
PrivateRoute组件? -
@aleksxor 你现在可以检查一下吗??
-
当它给你错误时,你在哪里插入带有
useAuthContext的行? -
@aleksxor 我在
component中使用useAuthContext传递给PrivateRoute(这里是Home)。 ContextProvider 环绕Switch
标签: reactjs typescript react-router-dom