【问题标题】:React Uncaught ReferenceError: Buffer is not definedReact Uncaught ReferenceError:未定义缓冲区
【发布时间】:2022-01-21 23:47:31
【问题描述】:

我通过运行 npx create-react-app my-app 创建了一个 React 项目

我安装了 mqtt-react-hooks

我添加了 App 脚本

import { Connector } from 'mqtt-react-hooks';

import Status from './Status';

function App() {
    return (
        <Connector
          brokerUrl="mqtt://127.0.0.1:80/"
          parserMethod={(msg) => msg} // msg is Buffer
        >
          <Status />
        </Connector>
  );
}

export default App;

我在控制台中收到此错误

【问题讨论】:

标签: reactjs mqtt


【解决方案1】:

我也有这个问题。

最近我创建了一个新版本的 react 应用程序,当我使用 mqtt.js(不是 mqtt-react-hooks)时,出现了这个错误!!!

我发现 Webpack 版本 5 不支持 Buffer 等等。 Webpack 5 移除了 Buffer(参见 this 信息),有效地破坏了 MQTT 库,因为它在代码中明确使用了它。

所以我降级到 Webpack 4 并且它工作正常。 如果您不知道如何操作,此链接可能会有所帮助。 How to downgrade version of Webpack?.

【讨论】:

    【解决方案2】:

    我看到你没有在文件顶部导入 React, 要编写 jsx 代码,您需要有 import React from 'react'

    【讨论】:

    • 如果 react 版本为 17 或以上,我们可能不需要导入 react 来编写 jsx。
    猜你喜欢
    • 2022-01-28
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 2021-10-12
    • 2022-01-14
    相关资源
    最近更新 更多