如何使用 Promises 创建受保护的路由

How to create a Protected Route with Promises

我正在使用钩子来保护我的路线。我遇到的问题是检查用户身份验证状态的调用 returns 是一个 Promise,因此挂钩 returns 是默认值,即 a 然后身份验证状态不再是很有用,因为我们已经重定向了。

那么我如何才能等待 return 从 hook 直到完成身份验证检查?这是我的代码:

export function ProtectedRoute(props){

const [loggedIn, setLoggedIn] = useState(false);

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
    async function fetchUser() {
        let user = null;

        try {
            user = await Auth.currentAuthenticatedUser()
            if (user) {
                setLoggedIn(true);
            } else
            {
                setLoggedIn(false);
            }
        } catch (e) {
            setLoggedIn(false);
        }
    }
    fetchUser()
});

console.log("ProtectedRoute: returning " + loggedIn);
if (loggedIn)
    return props.component
else
    return <Redirect to={{pathname: '/login'}}/>

}

我会添加一个新状态,loading,直到 true,只渲染一个加载组件:

    export default ProtectedRoute(props) {
    
      const [loggedIn, setLoggedIn] = useState(false);
      const [loading, setLoading] = useState(true);
      
      useEffect(() => {
        (async () => {
          try {
            setLoading(true);
            const user = await Auth.currentAuthenticatedUser();
            setLoggedIn(!!user);
          } catch (error) {
            console.log(error);
            setLoggedIn(false);
          } finally {
            setLoading(false);
          }
        })();
      }, []);
    
      if(loading) return <h1>Loading...</h1>;
        
      if (loggedIn) return props.component
    
      return <Redirect to={{ pathname: '/login' }}/>
  }

找到解决方案...必须默认为 isAuthenticated 'true',然后如果不是这种情况则重定向(重定向似乎在我的初始代码中打破了我的逻辑)

export function ProtectedRoute({ component: Component, ...rest }){

const [isAuthenticated, setLoggedIn] = useState(true);
useEffect(() => {
    (async () => {
        let user = null;

        try {
            user = await Auth.currentAuthenticatedUser()
            if (user) {
                setLoggedIn(true);
            } else
            {
                setLoggedIn(false);
            }
        } catch (e) {
            setLoggedIn(false);
        }
    })();
});

return (
    <Route
        {...rest}
        render={props =>
            isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
        }
    />
);

}