未捕获的错误:渲染的钩子数量少于预期。这可能是由于意外提前返回语句造成的。这是代码。我正在关注 freecodecamp 的 YouTube 教程。在该教程中它工作正常,但在我这边,它工作得不好。我期待渲染 APi 中存在的不同产品图像。相反,我收到此错误:
import React, { useEffect, useState } from "react";
import "./style.css";
export default function LoadMoreImages() {
const [products, setProducts] = useState([]);
const [count, setCount] = useState(0);
const [loading, setLoading] = useState(false);
const [disableButton, setDisableButton] = useState(false);
async function fetchingProducts() {
try {
setLoading(true);
const response = await fetch(
`https://dummyjson.com/products?limit=20&skip=${
count === 0 ? 0 : count * 20
}`
);
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(() => {
fetchingProducts();
}, [count]);
if (loading) {
return <div>Loading Data! Please wait for sometime</div>;
}
useEffect(() => {
if (products && products.length === 100) setDisableButton(true);
}, [products]);
return (
<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>
</div>
))
: null}
</div>
<div className="button-container">
<button disabled={disableButton} onClick={() => setCount(count + 1)}>
Load More Products
</button>
{disableButton ? <p>You have reached 100 products</p> : null}
</div>
</div>
);
}
你不能将react hooks代码放在条件语句之后,例如
if...else
useEffect(() => {
if (products && products.length === 100) setDisableButton(true);
}, [products]);
if (loading) {
return <div>Loading Data! Please wait for sometime</div>;
}