useEffect 无限循环时尝试检查用户是否已登录



我使用 auth0,当应用程序可能在页面刷新时重新呈现时,我尝试使用 auth0 做几件事,第一个是检查用户是否经过身份验证,如果他将他的令牌和用户对象保存在 mobx 存储中,否则将他重定向到登录页面。 这是 IM 当前使用的代码:

// appLoaded --> to check if the user is logged in (app cannot be used without a user)
const App: React.FC = () => {
const {
// isAuthenticated,
user,
getIdTokenClaims,
loginWithRedirect,
isAuthenticated
} = useAuth0();
const {
sideNavStore: { isOpen, toggleSideBar },
authStore: { setAppLoaded, setToken, setUser, appLoaded }
} = useStore();
// get the user from auth0 and store their details in the mobx store;
useEffect(() => {
if (isAuthenticated) {
getIdTokenClaims().then((response) => {
// eslint-disable-next-line no-underscore-dangle
setToken(response.__raw);
setUser(user);
});
} else {
loginWithRedirect().then(() => {
setAppLoaded(false);
});
}
}, [
isAuthenticated,
setToken,
setUser,
setAppLoaded,
loginWithRedirect,
getIdTokenClaims,
user
]);
if (!appLoaded) return <PreLoader />;
return (
// some component code
)}

我在上面的代码中遇到了无限循环。 我已经在这个问题上呆了一天了,只是决定在这里问。 谁能告诉我我做错了什么? 谢谢

不应从useEffect内部更新其所依赖的任何状态。这就形成了一个无限循环。

单个useEffect的依赖项太多,并且正在更新其中一些依赖项。将代码拆分为多个依赖项较少的useEffect,确保每个依赖项都不会更新自己的依赖项

最新更新