[英]How to call Auth0 loginWithRedirect function in React useEffect without button clicking?
在 React 应用程序中,我将实现 Auth0 登录,如下所示。 当用户访问/login
时,它将检查用户是否经过身份验证。
这是代码。
import React from 'react';
import { useHistory } from "react-router-dom";
import { useAuth0 } from "@auth0/auth0-react";
import SplashScreen from "src/components/SplashScreen";
const LoginView = () => {
const { loginWithRedirect, isAuthenticated } = useAuth0();
const history = useHistory();
React.useEffect(() => {
if (isAuthenticated) {
history.push("/explore");
} else {
loginWithRedirect();
}
}, [isAuthenticated])
return <SplashScreen />;
};
export default LoginView;
但是当我从 Auth0 登录页面登录时,我会被重定向到 React 应用程序的/login
页面,并且它会无限循环。 我尝试像上面的代码一样在控制台上注销isAuthenticated
值,但即使我正确登录了 Auth0 身份验证页面,它也是false
的。
请让我知道如何解决这个问题。 谢谢。
此代码正在运行。
import React from 'react';
import axios from 'axios';
import { useHistory } from "react-router-dom";
import { useAuth0 } from "@auth0/auth0-react";
import SplashScreen from "src/components/SplashScreen";
const LoginView = () => {
const { isAuthenticated, loginWithRedirect } = useAuth0();
const history = useHistory();
React.useEffect(() => {
async function checkUser() {
if (isAuthenticated) {
await history.push("/explore");
} else {
loginWithRedirect();
}
}
checkUser();
}, [isAuthenticated, loginWithRedirect]);
return (
<SplashScreen />
);
}
export default LoginView;
我使用了以下模式源: https://thinkster.io/tutorials/auth0-react-login-and-user-profile/protect-the-profile-route
const { loading, isAuthenticated, loginWithRedirect } = useAuth0();
useEffect(() => {
if (loading || isAuthenticated) {
return;
}
const fn = async () => {
await loginWithRedirect({
appState: { targetUrl: path }
});
};
fn();
}, [loading, isAuthenticated, loginWithRedirect, path]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.