我正在学习 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中仍然无法解决问题
任何人都可以给我提示错误在哪里吗?谢谢你
您很可能需要从 index.js 文件中删除