【问题标题】:How to run useEffect before render for authentication如何在渲染之前运行 useEffect 进行身份验证
【发布时间】:2022-02-10 15:54:35
【问题描述】:

我有阅读组件,它必须仅在用户登录时显示。如果用户未通过身份验证,我现在将用户重定向到 /login 页面。但是在重定向过程中,阅读页面会显示几毫秒,允许未经身份验证的用户在重定向过程中看到阅读页面的闪烁。

我尝试使用 useLayoutEffect 而不是 useEffect 但同样的闪烁发生。也尝试不使用 useEffect 或 useLayoutEffect 并在函数内,但仍然相同

我从全局状态获取 userInfo,它从 cookie 获取 userInfo。对于状态管理,我使用反冲。

阅读页面:(必须受到保护,如果没有用户,则重定向到登录页面)

function index() {
  const router = useRouter();
  const userInfo = useRecoilValue(userAtom);   ---> userInfo is recoil global state

  useLayoutEffect(() => {
    if (!userInfo) {
      router.push("/login?redirect=/reading");
    }
  }, []);

  return (//some code)

注意: 添加加载器有效,但有没有更好的方法?

【问题讨论】:

  • 如果没有userInfo,则不返回任何内容,如果(!userInfo)返回null;
  • 试过了,但 useEffect 在渲染后仍然运行,对吗?所以,当给定 null 时会发生同样的问题
  • 所以你必须在服务器端重定向,检查这个question

标签: reactjs next.js recoiljs


【解决方案1】:
  1. 检查身份验证状态
  2. 显示基于身份验证状态的加载器
  3. 重定向用户

【讨论】:

    【解决方案2】:

    我会建议一个更好的方法。而不是检查单个页面。

    您可以在路由级别为用户编写身份验证检查,即在定义 React-Router 的 index.js 内。

    // PrivateRoute.jsx
    function PrivateRoute ({component: Component, isAuth, ...rest}) {
      return (
        <Route
          {...rest}
          render={(props) => isAuth
            ? <Component {...props} />
            : <Redirect to={{pathname: '/login', state: {userInfo} }} />}
        />
      )
    }
    
    // index.jsx
    .
    const userInfo = useRecoilValue(userAtom); 
    .
    <Route path='/login' component={Login} />
    <Route path='/register' component={Register} />
    <PrivateRoute isAuth={!!userInfo} userInfo={userInfo} path='/dashboard' component={Dashboard} />
    .
    .
    

    希望这会有所帮助。

    【讨论】:

    • 是的,这适用于 react,但我使用 nextjs
    • @SaiKrishnadas 尝试将您的if 条件转移到useLayoutEffect 钩子之外,写在const userInfo = useRecoilValue(userAtom) 之后。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 2013-10-15
    • 2021-10-12
    相关资源
    最近更新 更多