You need to enable JavaScript to run this app. React Context API展示产品数组异常:引入ProductBrowse报render非函数错误
优惠活动
大模型
产品
解决方案
定价
更多

React Context API展示产品数组异常:引入ProductBrowse报render非函数错误

报错核心原因

你遇到的 TypeError: render is not a function 完全是因为ProductConsumer的使用不符合React Context的规范:

  • Context.Consumer 组件的唯一要求是:children必须是一个返回JSX的函数,组件内部会自动调用这个函数,把当前Context的数值作为参数传入,最终渲染函数返回的内容。
  • 你现在的写法,把<Grid>组件作为了ProductConsumer的直接子元素,把原本应该作为Consumer渲染回调的函数放在了Grid的children位置。当Consumer内部尝试执行children(Context值)时,拿到的children是一个React元素对象,不是可执行的函数,自然就会抛出“无法调用非函数类型的render”的错误。

之前没引入ProductBrowse时你能看到Context数据的日志,本质是当时还没触发Consumer对children的校验逻辑,只是提前打了测试日志,写法从一开始就不符合Consumer的使用规则。

具体修复方法

调整JSX层级,把Context的渲染回调函数直接作为ProductConsumer的children,不要在Consumer和回调函数之间嵌套其他元素,修复后的代码参考:

<ProductConsumer>
  {/* 回调函数直接作为Consumer的children */}
  {(value) => {
    return (
      <Grid container spacing={3}>
        {value.products.map((prod, idx) => (
          <Grid item xs={3} key={`${prod.name}-${prod.store}-${idx}`}>
            <ProductBrowse
              productName={prod.name}
              productDesc={prod.desc}
              productImg={prod.img}
              productPrice={prod.price}
            />
          </Grid>
        ))}
      </Grid>
    )
  }}
</ProductConsumer>
额外检查项
  • 确认ProductBrowse组件引用的useStyles、formatCurrency、ProductModal这些依赖都有正确导入,不存在未定义的引用。
  • 可以删掉ProductStyling标签末尾的孤立分号,不影响运行但会让代码更整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.27 04:54:08