You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Brewdog API的React卡片组件无法渲染求助

求助:Brewdog API项目中卡片组件无法渲染

我正在开发一个调用Brewdog API的项目,需要把各类啤酒信息渲染到卡片组件里,但目前卡片组件完全不显示。已经在App.jsx里完成了API数据获取,通过props把数据从CardArea逐层传到Card组件,React Devtools显示啤酒对象数组已经成功传递,而且没有编译错误和控制台报错,求各位帮忙看看问题出在哪!

App.jsx

import { useState, useEffect } from 'react'
import styles from './App.module.scss'
import NavBar from "./components/NavBar";
import CardArea from "./components/CardArea";

const App = () => {
  const [beers, setBeers] = useState([])

  const getBeerData = () => {
    const API_URL = "https://api.punkapi.com/v2/beers"

    fetch(API_URL)
      .then((res) => res.json())
      .then((jsonResponse) => {
        setBeers(jsonResponse)
      })
      .catch(err => console.error('API请求出错:', err))
  }

  useEffect(() => {
    getBeerData()
  }, [])

  return (
    <>
      <main className={styles.main}>
        <NavBar />
        <CardArea beers={beers}/>
      </main>
    </>      
  );
}

export default App;

CardArea.jsx

import styles from './CardArea.module.scss'
import CardList from '../CardList/CardList'
import NotFound from '../NotFound/NotFound'

const CardArea = (props) => {
  const { beers } = props;

  const contentJsx = beers.length ? (
    <CardList beers={beers} />
  ) : (
    <NotFound />
  );

  return <section className={styles.cardArea}>{contentJsx}</section>
}

export default CardArea;

CardList.jsx

import Card from '../Card/Card'
import styles from './CardList.module.scss'

const CardList = (props) => {
  const { beers } = props;

  const getBeerCardsJsx = (beer) => {
    return (
      <div className={styles.card} key={beer.id}>
        <Card beer={beer} />
      </div>
    )
  }

  return <section className={styles.cards}> {beers.map(getBeerCardsJsx)} </section>
}

export default CardList

Card.jsx

import React from 'react'
import styles from './Card.module.scss'

const Card = (props) => {
  const { name, tagline, abv, description, image_url } = props.beer;

  return (
    <div className={styles.card}>
      <img className={styles.img} alt={name} src={image_url} onError={(e) => e.target.style.display = 'none'} />
      <section>
        <h1>{name}</h1>
        <h4>{tagline}</h4>
        <p>ABV: {abv}%</p>
        <p>{description}</p>
      </section>
    </div>
  )
}

export default Card

问题分析与修复方案

  1. 核心问题:CardList组件的map回调无返回值
    原getBeerCardsJsx函数里写了JSX但没有return,导致beers.map()遍历后得到的全是undefined,自然没有任何内容渲染。只需要给函数加上return,或者改用箭头函数的简写形式(用括号包裹JSX自动返回)。

  2. 次要问题:Card组件的img缺少src属性
    原代码里的img标签没有设置src,所以图片不会显示,需要从props.beer里取出image_url赋值给src,同时可以加上onError处理图片加载失败的情况。

  3. 可选优化:API请求添加错误捕获
    在fetch的链式调用里加上.catch(),方便排查API请求可能出现的错误。

内容的提问来源于stack exchange,提问作者atc2206

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 14:36:26