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

React Native从WordPress API加载图片报错,寻求解决方案

React Native 从WordPress获取图片报错:undefined is not an object (evaluating 'item.og_image[2]')

问题描述

我正在做一个React Native学生项目,用于展示F1赛车,通过fetch从我的WordPress网站的帖子中获取标题、图片等数据。我用Postman找到了想要的图片数据结构:

"og_image": [
    {
        "width": 1920,
        "height": 1080,
        "url": "https://tibomertens.be/wp-content/uploads/2022/12/F1-75_JPG_SPONSOR_00004.jpg",
        "type": "image/jpeg"
    }
],

于是在代码中通过item.id === 572的条件渲染图片:

{item.id === 572 && (
    <Image
        style={{ width: 50, height: 200 }}
        source={{ uri: `${item.og_image[0].url}` }}
    />
)}

但出现错误:[TypeError: undefined is not an object (evaluating 'item.og_image[2]')]

完整代码:

const Cars = ({ navigation }) => {
  const [Cars, setCars] = useState([]);

  const getCars = async () => {
    try {
      const response = await fetch(
        "https://tibomertens.be/wp-json/wp/v2/posts?categories=8",
        {}
      );
      const json = await response.json();
      setCars(json);
      console.log(Cars);
      console.log("hey");
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    getCars();
  }, []);

  return (
    <View>
      <FlatList
        data={Cars}
        renderItem={({ item }) => (
          <View>
            <Text>
              {"\n"}
              {item.id === 572 && (
                <Image
                  style={{ width: 50, height: 200 }}
                  source={{ uri: `${item.og_image[0].url}` }}
                />
              )}
              <Text>
                {item.title.rendered} {"\n"}{" "}
              </Text>
              <Text>{item.rttpg_excerpt}</Text>
            </Text>
            <Pressable
              onPress={() =>
                navigation.navigate("Details", {
                  itemTile: item.title.rendered,
                })
              }
            >
              <Text>bekijk product</Text>
            </Pressable>
          </View>
        )}
      ></FlatList>
    </View>
  );
};

解决方案

1. 添加严格的空值检查

错误核心是尝试访问不存在的对象/数组元素,可能是:

  • id为572的帖子未返回og_image字段
  • 数据加载完成前,item或item.og_image为undefined
  • 代码其他地方误写了og_image[2](需检查遗漏的渲染逻辑)

修改图片渲染条件,添加空值校验:

{item.id === 572 && item.og_image && item.og_image.length > 0 && (
    <Image
        style={{ width: 50, height: 200 }}
        source={{ uri: item.og_image[0].url }}
    />
)}

2. 修复异步状态的日志问题

setCars是异步操作,当前console.log(Cars)会输出初始空数组,无法查看实际返回数据。修改getCars函数:

const getCars = async () => {
  try {
    const response = await fetch(
      "https://tibomertens.be/wp-json/wp/v2/posts?categories=8",
      {}
    );
    const json = await response.json();
    console.log("返回的数据:", json); // 查看实际返回的所有帖子数据
    setCars(json);
  } catch (error) {
    console.error(error);
  }
};

3. 添加加载状态(可选)

避免数据未加载完成时FlatList渲染空数据导致的异常:

const Cars = ({ navigation }) => {
  const [cars, setCars] = useState([]);
  const [loading, setLoading] = useState(true); // 添加加载状态

  const getCars = async () => {
    try {
      const response = await fetch(
        "https://tibomertens.be/wp-json/wp/v2/posts?categories=8",
        {}
      );
      const json = await response.json();
      setCars(json);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false); // 无论成功失败都结束加载
    }
  };

  useEffect(() => {
    getCars();
  }, []);

  // 加载中时显示占位
  if (loading) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>加载中...</Text>
      </View>
    );
  }

  return (
    <View>
      <FlatList
        data={cars}
        renderItem={({ item }) => (
          <View>
            <Text>
              {"\n"}
              {item.id === 572 && item.og_image && item.og_image.length > 0 && (
                <Image
                  style={{ width: 50, height: 200 }}
                  source={{ uri: item.og_image[0].url }}
                />
              )}
              <Text>
                {item.title.rendered} {"\n"}{" "}
              </Text>
              <Text>{item.rttpg_excerpt}</Text>
            </Text>
            <Pressable
              onPress={() =>
                navigation.navigate("Details", {
                  itemTile: item.title.rendered,
                })
              }
            >
              <Text>bekijk product</Text>
            </Pressable>
          </View>
        )}
      />
    </View>
  );
};

额外提示

  • 检查WordPress返回的所有帖子数据,确认id为572的帖子确实包含og_image数组且长度至少为1
  • 变量名建议用小驼峰(比如cars而非Cars),避免和组件名冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:30:41