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

React食谱应用API分类查询无数据问题求助

问题解决方案

1. API请求参数错误

Spoonacular的complexSearch接口中,指定菜系的参数是cuisine而非variety,原代码参数名错误导致API无法返回对应数据。

修复后请求URL:

const data = await fetch(`https://api.spoonacular.com/recipes/complexSearch?apiKey=${process.env.REACT_APP_API_KEY}&cuisine=${name}`)

2. API响应数据取值错误

Spoonacular返回的结果数组是results(复数形式),原代码写成了recipe.result(单数),导致无法正确赋值状态。

修复后状态赋值:

setVariety(recipe.results);

3. JSX返回语法错误

return后直接换行且未用括号包裹JSX,导致组件返回undefined,页面无内容渲染。

修复后return部分:

return (
  <Grid>
    {variety.map((item)=>{
      return(
        <Card key={item.id}>
          <img src={item.image} alt={item.title}/>
          <h4>{item.title}</h4>
        </Card>
      )
    })}
  </Grid>
)

4. 组件导入路径错误

Pages组件中导入Variety时路径末尾有空格:import Variety from './Variety ';,会导致React无法找到组件文件。

修复后导入语句:

import Variety from './Variety';

可选优化:添加错误处理与加载状态

为避免请求失败或数据未加载时页面空白,可补充错误捕获和loading状态逻辑,以下是修正后的完整Variety组件:

import React, { useEffect, useState } from 'react'
import styled from 'styled-components'
import { useParams } from 'react-router-dom'

export default function Variety () {
  const [variety, setVariety] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const params = useParams();

  const getVariety = async (name) => {
    setLoading(true);
    try {
      const data = await fetch(`https://api.spoonacular.com/recipes/complexSearch?apiKey=${process.env.REACT_APP_API_KEY}&cuisine=${name}`);
      if (!data.ok) throw new Error('请求失败');
      const recipe = await data.json();
      setVariety(recipe.results);
      setError(null);
    } catch (err) {
      setError(err.message);
      setVariety([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(()=>{
    getVariety(params.type);
  },[params.type]);

  if (loading) return <div>加载中...</div>;
  if (error) return <div>错误:{error}</div>;

  return (
    <Grid>
      {variety.length === 0 ? (
        <div>暂无该菜系的食谱</div>
      ) : (
        variety.map((item)=>{
          return(
            <Card key={item.id}>
              <img src={item.image} alt={item.title}/>
              <h4>{item.title}</h4>
            </Card>
          )
        })
      )}
    </Grid>
  )
}

const Grid = styled.div`
display:grid;
grid-template-columns:repeat(auto-fit,minmax(20rem,1fr));
grid-gap:3rem
`
const Card = styled.div`
img{
width:100%;
border-radius:2rem;
}

a{
text-decoration:none;
}

h4{
text-align:center;
margin:2rem;
}
`

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:49:51