简体   繁体   English

在 React 应用程序上获取数据时如何添加加载微调器?

[英]How can I add loading spinner while fetching data on react app?

How to add loading spinner while fetching.如何在获取时添加加载微调器。 I want to add loading spinner on fetch data on my react app.我想在我的反应应用程序上添加加载微调器来获取数据。

you can use react Suspense and lazy for it.你可以为它使用 React Suspense and lazy here below is a code example.下面是一个代码示例。

import { Suspense, lazy } from "react";

import Loading from "./loading";
const Loaded = lazy(() => import("./loaded"));

const App = () => {
  return (
    <Suspense fallback={<Loading />}>
      <Loaded />
    </Suspense>
  );
};

you can read mode about the suspense here suspense你可以在这里阅读关于悬念的模式suspense

here is sandbox Link sanbox这是沙盒链接sanbox

You need to have a loading state based on how you are fetching the data for example if you are fetching data using axios you need to set the loading to true in the beginning of your fetch function and set it to false on receiving data or on error.您需要根据获取数据的方式加载 state 例如,如果您使用axios获取数据,则需要在获取开始时将加载设置为 true function 并在接收数据或出错时将其设置为 false .

const App = () => {
  const [loading, setLoading] = useState(false);

  const fetchFunction = () => {
    setLoading(true);
    .
    .
    .
    if (data || error) {
      setLoading(false);
    }
  };

  if (loading) return <Loading />;

  return <Data />;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM