为什么我的代码在页面加载时两次获取相同的项目?

问题描述 投票:0回答:1

我正在学习 React 并尝试获取产品列表的一些数据。

最初应该只获取 2 个项目,然后在按下按钮时再获取 2 个项目,但现在在页面首次加载时会获取相同的项目两次。

import { useEffect, useState, Fragment } from 'react';
import './style.css';

export default function LoadMoreData() {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState([]);
  const [count, setCount] = useState(0);
  const [disableButton, setDisableButton] = useState(false);

  const loadLimit = 10;
  let limit = 2;

  async function fetchProducts() {
    const dataUrl = `https://dummyjson.com/products?limit=${limit}&skip=${
      count === 0 ? 0 : count * limit
    }`;

    try {
      setLoading(true);
      const response = await fetch(dataUrl);
      const result = await response.json();

      if (result && result.products && result.products.length) {
        setProducts((prevData) => [...prevData, ...result.products]);
        setLoading(false);
      }

      console.log(result);
    } catch (e) {
      console.log(e);
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchProducts();
  }, [count]);

  useEffect(() => {
    if (products && products.length === loadLimit) setDisableButton(true);
  }, [products]);

  if (loading) {
    return <div>Loading data! Please wait.</div>;
  }

  return (
    <Fragment>
      <div className='load-more-container'>
        <div className='product-container'>
          {products && products.length
            ? products.map((item) => (
                <div className='product' key={item.id}>
                  <img src={item.thumbnail} alt={item.title} />
                  <p>{item.title}</p>
                  <span>$ {item.price}</span>
                </div>
              ))
            : null}
        </div>
        <div className='button-container'>
          <button disabled={disableButton} onClick={() => setCount(count + 1)}>
            Load more products
          </button>
          {disableButton ? (
            <p>You have reached to {loadLimit} products!.</p>
          ) : null}
        </div>
      </div>
    </Fragment>
  );
}

我以为这个bug可能是因为我把async函数放在useEffect之外,但即使放在useEffect中仍然无法解决问题

任何人都可以给我提示错误在哪里吗?谢谢你

javascript reactjs async-await fetch-api
1个回答
0
投票

您很可能需要从 index.js 文件中删除

© www.soinside.com 2019 - 2024. All rights reserved.