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

React v6出现“函数不能作为React子元素”报错,请求排查代码问题

错误原因及修复方案

核心报错原因

你遇到的Functions are not valid as a React child报错,本质是React Router v6的element属性使用不符合规范:

React Router v6的element属性要求直接传入可渲染的JSX元素,不能传入返回JSX的函数,你在App.js的路由配置里给element传了箭头函数,React渲染时直接拿到了函数本身而不是可渲染的组件实例,就触发了这个报错。

具体修复步骤

找到App.js中如下错误的路由配置:

<Route exact 
  path="/dashboard" 
  element={()=> (<Dashboard {...props} nestedRoute={Home} />)} 
/>
<Route exact 
  path="/dashboard/addProduct" 
  element={()=> (<Dashboard {...props} nestedRoute={AddProduct} />)} 
/>

删除包裹组件的箭头函数,直接传入JSX元素即可:

<Route exact 
  path="/dashboard" 
  element={<Dashboard {...props} nestedRoute={Home} />} 
/>
<Route exact 
  path="/dashboard/addProduct" 
  element={<Dashboard {...props} nestedRoute={AddProduct} />} 
/>

额外可修复的逻辑问题

你Dashboard组件中的导航激活逻辑存在变量名不匹配的问题,会导致激活状态不生效:

const possibleRoutes = [
  { routes: "/dashboard", targetId: "home" }, // 此处定义的键名为routes
  { routes: "/addProduct", targetId: "addProduct" },
  { routes: "/products", targetId: "products" },
  { routes: "/profile", targetId: "profile" },
];
possibleRoutes.forEach(({ route, targetId }) => { // 此处解构的键名为route,和上面不匹配
  // 逻辑代码
})

把数组中的键名统一改为route即可修复:

const possibleRoutes = [
  { route: "/dashboard", targetId: "home" },
  { route: "/addProduct", targetId: "addProduct" },
  { route: "/products", targetId: "products" },
  { route: "/profile", targetId: "profile" },
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:06:04