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

Laravel结合Inertia使用React箭头函数组件为何报错?

Laravel + Inertia + React 箭头函数组件报错解决办法

在Laravel结合Inertia使用React时,会遇到一种情况:默认导出的函数组件能正常运行,但具名导出的箭头函数组件会报错。

正常运行的代码

import React from "react";

export default function All() {
    return <div>All</div>;
}

报错的代码

export const All = () => {
  return (
    <div>All</div>
  )
}

报错信息

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `Inertia`.

问题原因

Inertia加载React组件时,默认会查找默认导出(default export)的组件。上面报错的代码用的是具名导出(named export),Inertia找不到正确的组件函数,拿到的是模块导出的对象,导致React无法识别为有效组件,从而抛出错误。

解决办法

方法1:改为默认导出

这是最直接且符合Inertia常规用法的方式,把箭头函数组件改成默认导出即可:

export default () => {
  return (
    <div>All</div>
  )
}

或者拆分写法:

const All = () => {
  return (
    <div>All</div>
  )
}

export default All;

方法2:保持具名导出并明确导入

如果一定要用具名导出,需要在引用组件的地方明确指定导入具名组件。比如在其他React组件中导入时:

import { All } from './All';

同时要确保在Laravel的路由/控制器返回Inertia响应时,正确指向这个具名组件(不过这种方式相对繁琐,不推荐)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:27:08