微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

可观察状态未在功能中更新

如何解决可观察状态未在功能中更新

这是我用来验证用户的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,并且始终重定向登录屏幕,我们如何更新或维护函数中的状态?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。