简体   繁体   English

在未显示的反应应用程序中获取 api 时加载微调器

[英]Loading spinner while fetching an api in react app not showing

When the website loads for the first time the fetched data from an api don't show.But after one reload the products are shown .当网站第一次加载时,从 api 获取的数据不显示。但重新加载后,产品会显示。 Tried to use a loading spinner while loading the data.尝试在加载数据时使用加载微调器。 The spinner won't show either.微调器也不会显示。 How can I show the the loaded data on the first time and while loading the products the Loading spinner will be shown.如何在第一次显示加载的数据以及加载产品时显示加载微调器。

const [isLoading, setIsLoading] = useState(false);


 useEffect(() => {
setIsLoading(true);

fetch(" https://hidden-citadel-3557.herokuapp.com/inventory")
  .then((res) => res.json())
  .then((data) => setInventories(data));
setIsLoading(false );  }, []); `
  if (isLoading) {
return <Loading></Loading>  }

Move "setIsLoading(false)" to the second ".then", like this:将“setIsLoading(false)”移动到第二个“.then”,如下所示:

const [isLoading, setIsLoading] = useState(false);


 useEffect(() => {
   setIsLoading(true);

fetch(" https://hidden-citadel-3557.herokuapp.com/inventory")
  .then((res) => res.json())
  .then((data) => {
     setIsLoading(false);
     setInventories(data)
   });
 }, []); 

  if (isLoading) {
return <Loading></Loading>  }

Based on your code, your approach is not a very viable one.根据您的代码,您的方法不是很可行。

Here's what I would do.这就是我要做的。

  1. Use a separate function for loading the data.使用单独的函数来加载数据。
function loadData()
{
   setLoading(true);
   fetch(" https://hidden-citadel-3557.herokuapp.com/inventory")
     .then((res) => res.json())
     .then((data) => {
        setInventories(data);
        setLoading(false);
     });
}
  1. Then perform your effect:然后执行你的效果:
 useEffect(loadData,[]);
  1. In your jsx, use the loading variable to render <loading> element based on loading state varibale value:在您的 jsx 中,使用loading变量根据加载状态变量值呈现<loading>元素:

{ loading ? <loading></loading> : ""}

This works for me:这对我有用:

import React, { useState, useEffect } from "react";

const Index = () => {
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(
        "https://627a5a9773bad50685876437.mockapi.io/users"
      );
      await response.json();
      setIsLoading(false);
    };
    fetchData();
  }, []);

  return isLoading ? <p>Loading</p> : <p>Loaded!</p>;
};

export default Index;

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

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