这是我用来验证用户的userStore方法
@action loadUserByUserId = async () => {
try{
const serializedState = sessionStorage.getItem('state');
var userId = ''
if(serializedState !== null){
const jsonState = JSON.parse(serializedState);
userId = jsonState.oidc.user.profile.email;
}
const userDetails = await agent.User.loadUserByUserId(userId.toLocaleUpperCase());
runInAction('user found',() => {
this.isUserFound = true;
this.user = userDetails;
});
}
catch(error){
runInAction('user not found',()=>{
this.isUserFound = false;
this.user = null;
});
}
}
在对回调进行身份验证之后,将从OIDC提供程序发送到Callback.tsx下面,如果身份验证成功,则需要验证用户并导航到应用程序,否则重定向到登录屏幕 Callback.tsx
import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import { CallbackComponent } from "redux-oidc";
import userManager from "../../features/user/utils/userManager";
import { useHistory } from "react-router-dom";
import { LoadingComponent } from "./LoadingComponent";
import { useContext } from "react";
import { RootStoreContext } from "../stores/rootStore";
import { toast } from "react-toastify";
import { observer } from "mobx-react-lite";
const CallbackPage = (props:any) => {
const rootStore = useContext(RootStoreContext);
const {
loadUserByUserId,
user,
isUserFound
} = rootStore.userStore;
const history = useHistory();
const successCall =() =>{
console.log("Azure Ad Login Success");
console.log(user);
loadUserByUserId();
if(isUserFound){
window.localStorage.setItem('isLoggedIn','true');
history.push('/welcome');
}
else{
window.localStorage.setItem('isLoggedIn','false');
history.push('/');
toast.error("User Not Found, Please add User");
}
}
return (
<CallbackComponent
userManager={userManager}
successCallback={successCall}
errorCallback={error => {
window.localStorage.setItem('isLoggedIn','false');
history.push('/');
console.error(error);
}}
>
<div><LoadingComponent content='Authenticating ...' /></div>
</CallbackComponent>
);
}
export default connect()(observer(CallbackPage));
问题是即使执行完函数调用后isUserFound的值仍为false,并且始终重定向到登录屏幕,我们如何更新或维护函数中的状态?