如何在React useEffect中调用Auth0 loginWithRedirect函数而无需单击按钮?



在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值,就像上面的代码一样,但它是false,即使我正确地登录了Auth0认证页面。

请告诉我如何解决这个问题。谢谢。

代码运行正常

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 { isAuthenticated, loginWithRedirect } = useAuth0();
const history = useHistory();
React.useEffect(() => {
async function checkUser() {
if (isAuthenticated) {
await history.push("/explore");
} else {
loginWithRedirect();
}
}
checkUser();                            // called async checkUser()
}, [isAuthenticated, loginWithRedirect]); // added 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]);

最新更新