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

React Native项目调用Yelp API遇'undefined is not an object'错误求助

解决React Native中Yelp API数据渲染的"undefined is not an object"错误

错误原因分析

你的错误主要来自三个核心问题:

  1. API请求失败或返回异常时,json.businesses会变成undefined,直接赋值给recipeData后,组件尝试对undefined执行map操作触发报错
  2. 初始状态设置错误,把localRestaurants额外包裹了一层数组,导致后续数据结构混乱
  3. 过滤代码存在拼写错误:filer应为filter

具体修复方案

1. 处理API返回的异常情况

在处理Yelp API返回数据时,先判断json.businesses是否存在,同时捕获请求错误,避免直接赋值undefined:

const getRecipeFromYelp = () => {
  const yelpUrl = `https://api.yelp.com/v3/businesses/search?term=restaurants&location=${city}`;

  const apiOptions = {
    headers: {
      Authorization: `Bearer ${YELP_API_KEY}`,
    },
  };

  return fetch(yelpUrl, apiOptions)
    .then((res) => res.json())
    .then((json) => {
      // 兜底处理,确保始终是数组类型
      const businesses = json.businesses || [];
      setRecipeData(businesses);
    })
    .catch((err) => {
      // 打印错误便于调试
      console.error('Yelp API请求失败:', err);
      setRecipeData([]);
    });
};

2. 修正初始状态

如果localRestaurants本身就是数组,移除多余的数组包裹:

// 原错误代码:const [recipeData, setRecipeData] = React.useState([localRestaurants]);
const [recipeData, setRecipeData] = React.useState(localRestaurants);

若localRestaurants是单个对象,才需要用数组包裹,但根据后续渲染逻辑,它应该是数组类型。

3. 修正过滤代码的拼写错误

把filer改为正确的filter,同时保留兜底处理:

return fetch(yelpUrl, apiOptions)
  .then((res) => res.json())
  .then((json) => {
    const businesses = json.businesses || [];
    const filtered = businesses.filter((business) => 
      business.transactions.includes(activeTab.toLowerCase())
    );
    setRecipeData(filtered);
  })
  .catch((err) => {
    console.error('Yelp API请求失败:', err);
    setRecipeData([]);
  });

4. 组件渲染时增加兜底判断

在RecipeItems组件中,先校验recipeData的类型,确保只有数组才执行map:

export default function RecipeItems(props) {
  // 兜底处理,避免非数组数据触发报错
  const recipeList = Array.isArray(props.recipeData) ? props.recipeData : [];
  
  return (
    <TouchableOpacity activeOpacity={1} style={{ marginBottom: 30 }}>
        {recipeList.map((recipe, index) => (
            <View
                key={index}
                style={{
                marginTop: 10,
                padding: 15,
                backgroundColor: "white",
            }}>
                <RecipeImage image={recipe.image_url}/>
                <RecipeInfo
                    name={recipe.name}
                    rating={recipe.rating}
                />
            </View>
        ))}
    </TouchableOpacity>
  );
}

额外调试建议

  • 打开React Native调试工具,查看Network请求的返回结果,确认Yelp API是否正常返回businesses字段
  • 检查YELP_API_KEY是否有效、是否具备调用权限
  • 验证activeTab转小写后,是否与Yelp API返回的transactions字段格式匹配(比如Yelp返回的是delivery而非Delivery)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 03:24:38