【问题标题】:Invalid Hook Call in ReactTS with Route带有路由的 ReactTS 中的无效挂钩调用
【发布时间】: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

codesandbox

【问题讨论】:

  • 在应用程序中如何使用PrivateRoute组件?
  • @aleksxor 你现在可以检查一下吗??
  • 当它给你错误时,你在哪里插入带有useAuthContext 的行?
  • @aleksxor 我在component 中使用useAuthContext 传递给PrivateRoute(这里是Home)。 ContextProvider 环绕 Switch

标签: reactjs typescript react-router-dom


【解决方案1】:

现在可以了。

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="/" />
};

【讨论】:

  • 是的,我必须从 Route 中删除 Redirect
猜你喜欢
  • 2020-08-13
  • 2021-08-09
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2022-10-04
  • 1970-01-01
  • 2020-10-19
相关资源
最近更新 更多