0

Here I am having 4 components, where I am rendering all these four components in App.js. These four components individually hitting different APIs. So one component may render faster and others may render slower. What I am trying to achieve here is I need to show a loading indicator, till all components are rendered. I tried that using React Lazy loading and Suspense but no luck. Please help me with this. Here I am sharing the code of what I have done. Thanks in advance.

code:

import React, { Suspense, lazy } from "react";
import Navbar from "../layout/Navbar";
import Loader from "../layout/Preloader";

const Bar = lazy(() => import("./bar"));
const VariablePie = lazy(() => import("./variablePie"));
const Pie = lazy(() => import("./pie"));
const CombineChart = lazy(() => import("./combineChart"));

const Dashboard = () => (
  <div>
    <Navbar />
    <Suspense fallback={<Loader/>}>
      <main>
        <div className="row" style={{ backgroundColor: "#eee" }}>
          <div className="col s12 m6 l6" style={{ margin: "10px 0px" }}>
            <Bar />
          </div>
          <div className="col s12 m6 l6" style={{ margin: "10px 0px" }}>
            <VariablePie />
          </div>
          <div className="col s12 m6 l6" style={{ margin: "10px 0px" }}>
            <Pie />
          </div>
          <div className="col s12 m6 l6" style={{ margin: "10px 0px" }}>
            <CombineChart />
          </div>
        </div>
      </main>
    </Suspense>
  </div>
);

export default Dashboard;
4

1 回答 1

1

您想显示加载器,直到所有组件都被渲染,然后您可以在父组件(在您的情况下为仪表板)中有一个计数器变量,并在每个组件获取数据并准备好渲染时更新其值,在父组件中检查计数器是否等于所需加载组件的数量,然后渲染所有组件,否则继续渲染加载器。

这种方法有缺陷,如果任何 API 失败并且没有为该特定组件加载数据,那么在这种情况下,任何组件都不会显示在屏幕上。确保您也处理此类情况。

于 2020-03-21T06:08:27.013 回答