【问题标题】:How to load data from api and load component asynchronously with map function如何从api加载数据并使用map函数异步加载组件
【发布时间】:2021-02-25 14:35:19
【问题描述】:

我的后端数据库存储了数百个产品,我想以异步方式将它们列出给前端响应用户,而无需等到所有数据都加载完毕。虽然我使用 api 兑现,但仍然需要几秒钟才能将产品列表映射到组件。

我使用带有 axios 和 async/wait 函数的 useAPI 挂钩从 api 获取数据。

有什么方法可以改善加载并定期更新组件吗? 如何在前端缓存数据以避免对数据库的过度调用?

import React from "react";
import useAPI from '../../api/useAPI'
import { ProductsListWrap, ProductCard } from '../../components'

const ProductsList = (props) => {

   const handleSelect = (data) => {
      console.log(data)
   };
   
   const [products, loading, error, retry] = useAPI('/api/v1/products');
   return (
   <ProductsListWrap>
            {products.map((data, i) => {
              return (
                <ProductCard
                  handleSelect={() => handleSelect(data)}
                  key={i}
                  {...data}
                />
              );
            })}
    </ProductsListWrap>
  );
};

export default ProductsList;

   

【问题讨论】:

  • 您好,您是否尝试使用 useStateredux states 来存储和附加加载的产品?

标签: reactjs asynchronous axios react-hooks data-caching


【解决方案1】:

首先,您可能需要对请求进行分页..

您可以创建一个“缓存”,将状态添加到您的钩子。此外,您还需要在内部创建一个函数,以便随时发出请求。

在你的钩子中添加一个名为的函数,即fetchData(如果它不存在的话)。

同时返回 fetchData 函数。

function yourHook() {
  const [cache, setCache] = useState();

  function fetchData() {
    if (!cache) {
      // your axios logic
      setCache(response);
    }
  }

  ...

  return [fetchData, cache, loading, error, retry];
}

你的组件中调用fetchData(注意现在productscache):

const [fetchData, products, loading, error, retry] = useAPI('/api/v1/products');

useEffect(() => {
  fetchData();
}, []);

return (
  <ProductsListWrap>
    {products && products.map...}
  </ProductsListWrap>
);

【讨论】:

    猜你喜欢
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2013-09-24
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多