【问题标题】:ReactJs Lazy loading with conditionalReactJs 有条件的延迟加载
【发布时间】:2020-12-18 08:42:06
【问题描述】:

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

应用程序:

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:

【问题讨论】:

    标签: reactjs lazy-loading mobx


    【解决方案1】:

    您会出现这种行为,因为您在 App 组件中的效果会在每次组件呈现时运行。如果你只想在初始渲染后运行一次效果,你可以给它一个空数组作为第二个参数。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      相关资源
      最近更新 更多