我正在学习自定义钩子,但我很难理解我们如何能够设置和更新自定义钩子内定义的状态变量,并返回示例中所示的产品数组下面:
使用获取:
import { useState, useEffect, useCallback } from "react";
export const useFetch = (url) => {
const [loading, setLoading] = useState(false);
const [products, setProducts] = useState([]);
const getProducts = useCallback(async () => {
console.log(1);
setProducts(["teestingthis"]);
setLoading(true);
const response = await fetch(url);
const products = await response.json();
setLoading(false);
console.log(2);
setProducts(products);
setLoading(false);
}, [url]);
useEffect(() => {
getProducts();
console.log(3);
}, [url, getProducts]);
return { loading, products };
};
应用程序:
const url = "https://course-api.com/react-prop-types-example";
const Index = () => {
const { products, loading } = useFetch(url);
if (loading) {
return <p>Loading.....</p>;
}
return (
<div>
<h2>products</h2>
<section className="products">
{products.map((product) => {
return <Product key={product.id} {...product} />;
})}
</section>
</div>
);
};
export default Index;
我打算设置按钮来更新此产品结果,但我不确定如何访问 setProducts,因为它是在 useFetch 中定义的。
谢谢!