实际上,我试图在加载诸如男装、女装等按钮后获取API数据,但只显示了“加载”。按钮不显示。
当我尝试在componentMounted中初始化‘useEffect’时,所有的错误都会被删除,但是按钮不会显示。
import React, { useState, useEffect } from "react";
const Products = () => {
const [data, setData] = useState([]);
const [filter, setFilter] = useState(data);
const [loading, setLoading] = useState(false);
let componentMounted = true;
useEffect(() => {
const getProducts = async () => {
setLoading(true);
const response = await fetch("https://fakestoreapi.com/products");
if(componentMounted) {
setData(await response.clone().json());
setFilter(await response.json());
setLoading(false);
console.log(filter);
}
return () => {
componentMounted = false;
}
}
getProducts();
});
const Loading = () => {
return (<>Loading...</>);
};
const ShowProducts = () => {
return (
<>
<div className="button">
<button className="btn btn-outline-dark me-2">All</button>
<button className="btn btn-outline-dark me-2">Men's Clothing</button>
<button className="btn btn-outline-dark me-2">Women's Clothing</button>
<button className="btn btn-outline-dark me-2">Jewelery</button>
<button className="btn btn-outline-dark me-2">Electronics</button>
</div>
</>
);
};
return (
<>
<div className="container my-5">
<div className="row">
<div className="col-12">
<h1 className="display-6 fw-bolder text-center">Latest Products</h1>
<hr />
</div>
</div>
<div className="row justify-content-center">
{loading ? <Loading /> : <ShowProducts />}
</div>
</div>
</>
);
};
export default Products;错误信息是:
“在每次呈现后,从内部分配给'componentMounted‘变量React都会丢失。要保存该值,请将其存储在useRef钩子中,并将可变值保存在'.current’属性中。否则,可以将该变量直接移动到useEffect中。”
发布于 2022-10-16 13:29:33
它无法工作,因为没有提供依赖数组。如果没有提供依赖数组,那么组件将在无限循环中重新呈现。其次,为了使用卸载功能,您必须使用useEffect的返回函数。
您可以找到固定的示例这里。
发布于 2022-10-16 13:23:45
这是因为您忘记添加应该为空的依赖项数组一次,并且您可以在不需要时删除componentMounted,您的useEffect将如下所示:
useEffect(() => {
const getProducts = async () => {
setLoading(true);
const response = await fetch("https://fakestoreapi.com/products");
setData(await response.clone().json());
setFilter(await response.json());
setLoading(false);
console.log(filter);
};
getProducts();
}, []);https://stackoverflow.com/questions/74087402
复制相似问题