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

React Native报Object.entries参数不能为空错误 如何提取API返回的周数据

问题原因
  • 初始渲染时API请求尚未返回,你没有给nodesData设置空对象初始值,此时nodesData为undefined/null,传入Object.entries触发类型错误
  • JSX大括号内仅支持嵌入表达式,for...in是循环语句,不能直接在JSX中使用,因此抛出expression expected错误
  • 你代码中使用forEach遍历,forEach无返回值,无法渲染出遍历生成的组件
解决方案
  1. 给nodesData设置空对象初始值:
// 声明state时指定初始值
const [nodesData, setNodesData] = useState({});
  1. 遍历渲染时优先使用Object.keys(你只需要键名,不需要对应值,这个方法更适配需求),同时替换forEach为map:
return (
  {/* 你的外层容器代码 */}
  {Object.keys(nodesData).map(weekKey => (
    <View style={{ padding: 5 }} key={weekKey}>
      <View
        style={{
          flexDirection: "row",
          alignItems: "center",
        }}
      >
        <TouchableOpacity
          // 注意:navigation需要从组件props提前获取,不要从onPress的事件参数里取
          onPress={() => navigation.navigate("CoursesPlaylistScreen")}
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
            flex: 1,
          }}
        >
          <View
            style={{
              flexDirection: "row",
              justifyContent: "space-between",
              flex: 1,
            }}
          >
            <Text
              style={{
                fontSize: 16,
                color: "#000000",
                fontWeight: "bold",
              }}
            >
              {/* weekKey就是你要的week1、week2等周字段键名 */}
              {weekKey}
            </Text>
          </View>
        </TouchableOpacity>
      </View>
    </View>
  ))}
  {/* 你的其余代码 */}
)
  1. 可选兜底优化:如果不确定res.data一定返回对象,可以在赋值时加兜底:
setNodesData(res?.data ?? {});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:36:00