我有一个自定义路由,可以根据用户是否登录来呈现页面或将用户重定向到登录页面。
const AuthenticatedRoute = ({ children, ...rest }) => {
const auth = useContext(AuthContext);
const [isAuthenticated, setIsAuthenticated] = useState(null);
useEffect(() => {
const getAuth = async () => {
const res = await auth.isAuthenticated();
setIsAuthenticated(() => res);
};
getAuth()
}, [auth]);
return (
<Route
{...rest}
render={() => {
return isAuthenticated ? (
<>{children}</>
) : (
<Redirect to="/login" />
);
}}
></Route>
);
};
正如您在 useEffect
中看到的那样,我运行了一个异步方法。问题是每当组件想要挂载时,都会使用默认值 isAuthenticated
并将用户重定向到登录页面。我对如何处理这种情况有点困惑。我不希望在异步方法未完全运行时呈现组件。
答案 0 :(得分:0)
我相信它会在将 html 发送到客户端浏览器之前处理您的所有代码。