我正在学习React钩子,并尝试将类组件更改为功能组件,并使用useEffect和useState使用钩子获取数据,但是它不起作用。这是我的类组件,下面将放置功能组件的草稿,我认为使用useEffect的方式有问题。所有帮助将不胜感激。
import React, { useEffect, useState } from 'react';
const Shop = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
fetch(`/products`)
.then(response => response.json())
.then(response => {
setProducts(products);
});
})
return (
<div>
{
products.map(product => (
<div className="shop ml-5 mt-4" key={product.id}>
<img className="image" src={product.image} alt=""/><br></br>
<button className= "mt-4 btn btn-light">QUICKSHOP</button>
<button className="mt-4 btn btn-light">ADD TO CART</button>
<p className="mt-4"> {product.title}</p>
<p>{product.price}</p>
</div>
)) }
</div>
)
}
export default Shop;
所有帮助将不胜感激。
答案 0 :(得分:0)
在类组件中,您想在挂载上运行getProducts
,但在功能组件中,您要在每个渲染器上运行fetch
。向useEffect
添加一个空的依赖项数组,以确保它仅在安装时运行,而不是每次运行。
您还需要使用setProducts(response);
,而不是setProducts(products);
-products
是现有(空)状态。
useEffect(() => {
fetch(`/products`)
.then(response => response.json())
.then(response => {
setProducts(response);
});
}, [])