调用dummyJSON API获产品数据遇空数组,求简洁优化方案
问题分析与解决方案
问题根源
你调用的dummyJSON产品接口返回的是包含products数组的对象,结构为{products: Array(30), total: 100, skip: 0, limit: 30},但你的代码错误地把整个返回对象当成产品数组处理,同时链式调用里的then(console.log)会返回undefined,导致后续then接收的data无效,最终products状态被错误设置。
修正后的代码
const API_URL = 'https://dummyjson.com/products'; function App() { const [products, setProducts] = useState([]); const [cart, setCart] = useState([]); const [searchTerm, setSearchTerm] = useState(''); useEffect(() => { fetch(API_URL) .then(response => response.json()) .then(data => { // 直接提取返回对象中的products数组 if (data?.products && Array.isArray(data.products)) { setProducts(data.products); } }) .catch(error => console.error('Error fetching products:', error)); }, []); }
关键修正点
- 移除多余的
then(console.log),避免截断Promise数据流(如需打印日志,可在then(data => { ... })内部添加console.log(data)) - 直接访问返回数据的
data.products字段,这才是真正的产品数组,无需将整个对象转为数组 - 用可选链
data?.products和数组判断,避免API返回格式异常时触发报错
补充说明
你之前通过console.log(products[0].products)能拿到数据,是因为错误地把整个API返回对象放进了products数组(数组第一个元素就是完整的返回对象)。修正后products状态直接存储产品数组,后续可直接遍历使用。
内容的提问来源于stack exchange,提问作者Rick
相关产品推荐
相关产品推荐

