【问题标题】:Render an authentication protected component after an async authentication在异步身份验证后呈现受身份验证保护的组件
【发布时间】:2022-01-03 02:27:01
【问题描述】:

预期: async 函数检查用户是否通过身份验证,然后返回 true,以便呈现受保护的组件,或者返回 false,将用户重定向到登录页面。

实际发生的情况: getAuth() 函数返回“Promise”,破坏代码。

  export default function RequireAuth({ children, redirectTo }) {
  const BASE_API_URL = "https://api-backend.test";

  const getAuth = async () => {
    const isAuth = await axios
      .get(BASE_API_URL + "/user_auth.php", {
        withCredentials: true,
      })
      .then((res) => {
        if (res.status === 201) {
          return true;
        }
      })
      .catch((err) => {
        if (err.response.status === 401) {
          return false;
        }
      });

    return isAuth;
  };

  let isAuthenticated = getAuth();
  return isAuthenticated ? children : <Navigate to={redirectTo} />;
}

根据官方文档here,这就是“受保护”组件的显示方式。

<Route
  path="/dashboard"
  element={
    <RequireAuth redirectTo="/login">
      <Dashboard />
    </RequireAuth>
  }
/>

【问题讨论】:

    标签: javascript reactjs async-await react-router


    【解决方案1】:

    你必须正确使用useEffect,试试这个

    export default function RequireAuth({ children, redirectTo }) {
      const BASE_API_URL = "https://api-backend.test";
      const [isAuthenticated, setAuthenticated] = useState(false);
    
      useEffect(() => {
        const getAuth = () => {
          const isAuth = axios
            .get(BASE_API_URL + "/user_auth.php", {
              withCredentials: true
            })
            .then((res) => {
              if (res.status === 201) {
                setAuthenticated(true);
              }
            })
            .catch((err) => {
              if (err.response.status === 401) {
                setAuthenticated(false);
              }
            });
        };
    
        getAuth();
      }, [redirectTo]);
    
      if (isAuthenticated) {
        return children;
      }
      return <Navigate to={redirectTo} />;
    }
    

    【讨论】:

      【解决方案2】:

      getAuth 是一个异步函数,所以它会返回一个 Promise。您必须 await 其输出或使用 .then 来处理已解决的承诺。

      旁注,通常最好使用async/await 或.then,但不能同时使用。

      【讨论】:

        猜你喜欢
        • 2014-11-20
        • 1970-01-01
        • 2018-09-27
        • 1970-01-01
        • 1970-01-01
        • 2011-04-13
        • 2018-03-28
        • 2019-06-14
        • 2021-01-08
        相关资源
        最近更新 更多