ReactJs 有条件的延迟加载

ReactJs Lazy loading with conditional

您好,我遇到了如何使用异步调用加载我的组件的问题 基本上,当打开页面时,我会检查我的 api 用户是否有任何有效令牌(它是活动的),如果它不活动,则将呈现登录页面,如果不是,将呈现仪表板页面 但这给我带来了一个问题,当我没有连接时一切正常登录页面显示没有问题,但是当我在显示仪表板页面之前连接时它呈现登录页面,我陷入了如何解决这个问题的困境

APP:

const LoginPage = lazy(
  () => import(/* webpackChunkName: "LoginPage" */ './pages/login'),
);
const DashBoard = lazy(
  () => import(/* webpackChunkName: "DashBoard" */ './shared/infra/router'),
);
const AuthApp: React.FC<{isAuth: boolean; currentUser: any}> = observer(
  ({currentUser, isAuth}) => {
    return (
      <Suspense fallback={<h1>Loading profile...</h1>}>
        {isAuth && currentUser ? <DashBoard /> : <LoginPage />}
      </Suspense>
    );
  },
);

const App: React.FC = observer(() => {
  const {currentUserStore, authStore, layoutStore} = useRootStore();
  useEffect(() => {
    if (!currentUserStore.accessToken || !authStore.isAuth) authStore.initApi();
  });
  return (
    <ThemeProvider theme={layoutStore.isDarkMode ? darkTheme : lightTheme}>
      <GlobalReset />
      <AuthApp
        isAuth={authStore.isAuth}
        currentUser={currentUserStore.currentUser}
      />
    </ThemeProvider>
  );
});

export default App;

API 呼叫:我正在使用带有 RootStore

的 MOBX
  public initApi = async (): Promise<void> => {
    this.rootStore.authStore.inProgress = true;
    try {
      await this.rootStore.AxiosStore.get('/')
        .then((res) => {
          const decoded: any = jwtDecode(res.data.access_token);
          runInAction(() => {
            if (!(decoded instanceof Error)) {
              this.rootStore.currentUserStore.accessToken =
                res.data.access_token;
              this.rootStore.currentUserStore.currentUser = new UserModel({
                ...decoded,
                id: decoded.sub,
              });
            }
          });
        })
        .then(() =>
          runInAction(() => {
            this.rootStore.authStore.isAuth = true;
          }),
        );
    } catch (error) {
      console.log(error);
      const mute = error;
      runInAction(() => {
        this.rootStore.authStore.isAuth = false;
      });
    } finally {
      runInAction(() => {
        this.rootStore.authStore.inProgress = false;
      });
    }
  };

未记录 gif:

记录的 gif:

您之所以会出现此行为,是因为您的 App 组件 运行 每次渲染时都会产生效果。如果您只想 运行 在初始渲染后效果一次,您可以给它一个空数组作为第二个参数。

useEffect(() => {
  if (!currentUserStore.accessToken || !authStore.isAuth) authStore.initApi();
}, []);