如何在 react.js 中加载数据时添加微调器?

How to add spinner while loading data in react.js?

我想在从数据库加载数据时添加微调器。为了获取数据,我正在使用 react-hook。这是我的代码,如何在此处添加微调器?

import React from "react";
import { useNavigate } from "react-router-dom";
import useInventories from "../../../hooks/useInventories";
import Inventory from "../Inventory/Inventory";

const Inventories = () => {
const [inventories] = useInventories();

return (
    <>
      <div id="inventory" className="container mt-5 ">
        <h2 className="text-center my-5 text-primary ">Inventory</h2>
        <div className="row row-cols-1 row-cols-md-3 g-4 border-1 ">
          {inventories.slice(0, 6).map((inventory) => (
            <Inventory key={inventory._id} inventory={inventory}></Inventory>
          ))}
          
        </div>
        
      </div>
      
    </>
  );
};

export default Inventories;

  

从mongodb加载数据需要一点时间。所以我想在那之前添加微调器加载。

可以用useEffect解决。基本上初始加载是正确的,当您有库存数据时它会变为错误。我还看到您正在使用 tailwind,因此您可以直接使用 animate-spin

设置微调器图标动画
import React from "react";
import { useNavigate } from "react-router-dom";
import useInventories from "../../../hooks/useInventories";
import Inventory from "../Inventory/Inventory";

const Inventories = () => {
const [inventories] = useInventories();
const [loading, setLoading] = useState(true)

useEffect(() => {
    if(inventories?.length > 0) {
       setLoading(false)
  }

}, [inventories])

return (
    <>
      {loading <SpinnerComponent/> }
      {!loading
      <div id="inventory" className="container mt-5 ">
        <h2 className="text-center my-5 text-primary ">Inventory</h2>
        <div className="row row-cols-1 row-cols-md-3 g-4 border-1 ">
          {inventories.slice(0, 6).map((inventory) => (
            <Inventory key={inventory._id} inventory={inventory}></Inventory>
          ))}
          
        </div>
        
      </div>}
      
    </>
  );
};

export default Inventories;