[英]How to call Auth0 loginWithRedirect function in React useEffect without button clicking?
In React app, I was going to implement Auth0 login like the following.在 React 应用程序中,我将实现 Auth0 登录,如下所示。 When the user accesses the
/login
, it will check if the user is authenticated.当用户访问
/login
时,它将检查用户是否经过身份验证。
Here is the code.这是代码。
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;
But when I log in from the Auth0 login page, I am redirected to the /login
page of the React app, and it falls in looping indefinitely.但是当我从 Auth0 登录页面登录时,我会被重定向到 React 应用程序的
/login
页面,并且它会无限循环。 I tried to log out the isAuthenticated
value on the console like in the above code, but it is false
even though I logged in on the Auth0 authentication page correctly.我尝试像上面的代码一样在控制台上注销
isAuthenticated
值,但即使我正确登录了 Auth0 身份验证页面,它也是false
的。
Please let me know how I can solve this issue.请让我知道如何解决这个问题。 Thanks.
谢谢。
This code is working.此代码正在运行。
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;
I used the below pattern source: https://thinkster.io/tutorials/auth0-react-login-and-user-profile/protect-the-profile-route我使用了以下模式源: 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.