【问题标题】:Element type is invalid: expected a string (...) but got: object元素类型无效:应为字符串 (...) 但得到:对象
【发布时间】:2020-05-23 03:55:04
【问题描述】:

App.js

import React from 'react';
import ReactDOM from 'react-dom';

class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;

      }

}

export default Car;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Car from './App.js';

ReactDOM.render(<Car />, document.getElementById('root'));

我收到错误: 错误:元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

查看HotExportedComponent的渲染方法。

我知道导入指向正确的类。当我第一次在本地运行时,浏览器中会显示所需的文本“嗨,我是汽车!”。然后大约半秒后错误弹出。我认为这是错误消息中所示的热重载问题。我也为此使用了 Gatsby。

【问题讨论】:

标签: javascript reactjs components gatsby hot-reload


【解决方案1】:

Gatsby 使用 React 的内置解析,您无需像独立的 React 应用程序那样在 index.js 页面中导入 ReactDOM。只是:

import React from 'react';
// import ReactDOM from 'react-dom'; //remove it
import Car from './App.js';

const Index = ()=>{
   return <Car/>
}

export default Index;

【讨论】:

    猜你喜欢
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2017-11-02
    • 1970-01-01
    • 2020-03-11
    • 2019-11-25
    • 1970-01-01
    相关资源
    最近更新 更多