React + Antd + Rollup 组件库“错误:无效的钩子调用。钩子只能在函数组件体内调用”

2024-04-11

我目前正在构建一个 UI 库来简化跨多个应用程序的维护。这些目前使用 Ant Design。

一切似乎都很顺利...我在两者中都添加了我的对等依赖项package.json and rollup.config.js(通过外部)我能够让 Rollup 生成一个 es 和 cjs 二进制文件,并成功导出just我的代码。

但是,当我将其中任何一个导入到我的主机应用程序(Electron 和/或 React,已经使用 antd 没有问题)时,我收到以下错误:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (react.development.js:1476)
    at Object.useContext (react.development.js:1484)
    at Button (button.js:129)
    at renderWithHooks (react-dom.development.js:14985)
    at updateForwardRef (react-dom.development.js:17044)
    at beginWork (react-dom.development.js:19098)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994)
    at invokeGuardedCallback (react-dom.development.js:4056)
    at beginWork$1 (react-dom.development.js:23964)
resolveDispatcher @ react.development.js:1476
useContext @ react.development.js:1484
Button @ button.js:129
renderWithHooks @ react-dom.development.js:14985
updateForwardRef @ react-dom.development.js:17044
beginWork @ react-dom.development.js:19098
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22779
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
(anonymous) @ renderer.tsx:129
./src-template/renderer.tsx @ renderer.tsx:150
__webpack_require__ @ bootstrap:789
fn @ bootstrap:100
0 @ renderer.tsx:150
__webpack_require__ @ bootstrap:789
(anonymous) @ bootstrap:856
(anonymous) @ bootstrap:856
react-dom.development.js:20085 The above error occurred in the <Button> component:

    at Button (http://localhost:3000/main_window/index.js:48908:30)
    at ../../ui-library/dist/index.cjs.js.exports.ComponentA (http://localhost:3000/main_window/index.js:101188:13)
    at div
    at App (http://localhost:3000/main_window/index.js:204727:30)

我无法理解如何继续...我尝试调整我的汇总配置(如下)并将所有代码删除为单个测试器组件(antd Button),但我仍然遇到错误。

When I console.log()导入对象我可以看到 es 和 cjs 二进制文件都公开了测试器组件,但存在错误。

我在这里缺少什么?

对等依赖

  • React
  • 反应 DOM
  • antd
  • @ant-design/图标

Rollup.config.js

import { DEFAULT_EXTENSIONS } from '@babel/core'
import babel from '@rollup/plugin-babel'
import typescript from 'rollup-plugin-typescript2'
import commonjs from '@rollup/plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
import postcss from 'rollup-plugin-postcss'
import resolve from '@rollup/plugin-node-resolve'
import url from '@rollup/plugin-url'
import svgr from '@svgr/rollup'
import { terser } from 'rollup-plugin-terser'

import pkg from './package.json'


const isDevelopment = process.env.NODE_ENV === 'development' ? true : false;

console.log('EXPECTED EXTERNALS', [
      ...Object.keys(pkg.dependencies || {}),
      ...Object.keys(pkg.peerDependencies || {})
])
export default {
  input: 'src/index.jsx',
  output: [
    {
      file: `dist/index.es.js`,
      format: 'esm',
      exports: 'named',
      sourcemap: isDevelopment,
    },
    {
      file: `dist/index.cjs.js`,
      format: 'cjs',
      exports: 'named',
      sourcemap: isDevelopment,
    }
  ],
  context: 'this',
  external: [
        ...Object.keys(pkg.dependencies || {}),
        ...Object.keys(pkg.peerDependencies || {})
  ],
  plugins: [
    external(),
    typescript({
      rollupCommonJSResolveHack: true,
      clean: true,
      tsconfig: './tsconfig.json',
    }),
    babel({
      presets: [
        'react-app',
      ],
      extensions: [
        ...DEFAULT_EXTENSIONS,
        '.ts',
        '.tsx',
      ],
      plugins: [
        ["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }],
        "@babel/plugin-proposal-object-rest-spread",
        "@babel/plugin-proposal-optional-chaining",
        "@babel/plugin-syntax-dynamic-import",
        "@babel/plugin-proposal-class-properties",
        "transform-react-remove-prop-types"
      ],
      babelHelpers: 'runtime',
    }),
    postcss({
        extensions: ['.css', '.scss', '.less'],
        use: ['sass', ['less', {
          lessOptions: {
             javascriptEnabled: true
          }
        }]],
    }),
    svgr(),
    url(),
    resolve(),
    commonjs(),
    terser({ mangle: true }),
  ],
}

Package.json(组件库)

{
  "name": "ui-library",
  "version": "0.0.1",
  "description": "UI library components",
  "main": "index.js",
  "scripts": {
    "build": "rm -rf dist && mkdir dist && NODE_ENV=production BABEL_ENV=production rollup -c"
  },
  "peerDependencies": {
    "@ant-design/icons": "^4.3.0",
    "antd": "^4.9.2",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.10",
    "@babel/plugin-proposal-class-properties": "^7.12.1",
    "@babel/plugin-proposal-object-rest-spread": "^7.12.1",
    "@babel/plugin-proposal-optional-chaining": "^7.12.7",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/plugin-transform-react-jsx": "^7.12.10",
    "@babel/preset-env": "^7.12.10",
    "@babel/preset-react": "^7.12.10",
    "@babel/preset-typescript": "^7.12.7",
    "@rollup/plugin-babel": "^5.2.2",
    "@rollup/plugin-commonjs": "^17.0.0",
    "@rollup/plugin-node-resolve": "^11.0.0",
    "@rollup/plugin-typescript": "^8.0.0",
    "@rollup/plugin-url": "^6.0.0",
    "@svgr/rollup": "^5.5.0",
    "@types/node": "^14.14.11",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@typescript-eslint/eslint-plugin": "^4.9.1",
    "@typescript-eslint/parser": "^4.9.1",
    "babel-loader": "^8.2.2",
    "babel-plugin-import": "^1.13.3",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.24",
    "babel-preset-react-app": "^10.0.0",
    "css-loader": "^4.2.1",
    "eslint": "^7.15.0",
    "eslint-config-airbnb-typescript": "^12.0.0",
    "eslint-plugin-react": "^7.21.5",
    "less-loader": "^7.1.0",
    "mini-css-extract-plugin": "^1.3.2",
    "react-is": "^17.0.1",
    "rollup": "^2.34.2",
    "rollup-plugin-peer-deps-external": "^2.2.4",
    "rollup-plugin-postcss": "^4.0.0",
    "rollup-plugin-terser": "^7.0.2",
    "rollup-plugin-typescript2": "^0.29.0",
    "sass-loader": "^10.1.0",
    "style-loader": "^2.0.0",
    "typescript": "^4.1.2",
    "url-loader": "^4.1.1"
  }
}

组件库测试器组件

import React from 'react';

import { Button, Radio } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import { SizeType } from 'antd/lib/config-provider/SizeContext';


export interface ButtonProps {
  /**
   * What background color to use
   */
  backgroundColor?: string;
  /**
   * Button contents
   */
  label: string;

  /**
   * Size (small | large)
   */
  size: SizeType;
  /**
   * Optional click handler
   */
  onClick?: () => void;
}


// export const ComponentA = (props: ButtonProps) => (<button type="button" onClick={props.onClick} style={{ backgroundColor: props.backgroundColor}}>{ props.label }</button>);

export const ComponentA = (props: ButtonProps) => (
  <Button
    type="primary"
    shape="round"
    icon={<DownloadOutlined />}
    size={props.size || 'middle'}
    onClick={props.onClick || null}
  >
    {props.label || ''}
  </Button>
)

更新:添加了汇总插件可视化器输出


如果您在主项目中链接库的本地版本以加快开发速度时发生此问题。它可能与“React 的重复版本”有关。

https://reactjs.org/warnings/invalid-hook-call-warning.html https://reactjs.org/warnings/invalid-hook-call-warning.html

当您使用 npm link 或等效项时,也会出现此问题。在这种情况下,您的捆绑器可能会“看到”两个 React - 一个在应用程序文件夹中,一个在库文件夹中。假设 myapp 和 mylib 是同级文件夹,一种可能的修复方法是从 mylib 运行 npm link ../myapp/node_modules/react。这应该使库使用应用程序的 React 副本。

简而言之:

  • run npm link在 /your-app/node_modules/react.这应该会建立 React 的全局链接。
  • run npm link react在 /your-ui-library 中。这应该使库使用应用程序的 React 副本。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React + Antd + Rollup 组件库“错误:无效的钩子调用。钩子只能在函数组件体内调用” 的相关文章

随机推荐

  • 使用 gee() 拟合模型时出错:外部函数调用中出现 NA/NaN/Inf (arg 3)

    我正在一个包含 13 500 个观察值 这里是学生 的数据集上拟合一个 gee 模型 学生被分为 52 个不同的学校 我知道有证据表明学生嵌套在学校内 低 ICC 因此我应该在方差协方差矩阵中调整这种嵌套效应 我打算做的是首先安装一个具有可
  • 将 ls 输出转换为 csv

    我将如何转换 find ls gt tmp files txt 这给了我类似的东西 908715 40 rwxrwxr x 1 david staff 16542 Nov 15 14 12 dump info py 908723 0 drw
  • 将两个 PDF 页面合并为新页面,文本内容之间不留空格

    all 我想将两个 PDF 合并为一个 PDF 与此同时 我想无缝地加入这两个 PDF 例如 假设第一个PDF文件的最后一页有很多空白 合并后 我希望第二个PDF从第一个PDF的空白开始 我们有任何工具支持吗 这是一项并不难的任务 假设我们
  • 使用 xmllint 添加属性

    我想向标签添加一个属性 使用xmllint 我可以通过 xmllint 做到这一点吗 Xmllint 不是用来编辑 XML 的 所以我认为答案是 不 你不能 要编辑 XML 您可以使用 XMLStarlet 向现有 XML 文档添加属性的语
  • 无法从视图中的异步方法返回值

    我正在尝试从中返回值asynchtml 帮助器 但它给出以下字符串而不是所需的值 System Threading Tasks Task WhenAllPromise 1 System Decimal Method public async
  • 由于 zend 路线,zend 导航无法工作

    EDIT 该问题是由于 zend 路由引起的 请检查更新 我正在使用 xml 文件进行导航 编辑 以下代码来自layout phtml文件 config new Zend Config Xml APPLICATION PATH config
  • 您可以从 EntityListener 访问 EntityManager 吗?

    我知道 JSR 000220 Enterprise JavaBeans 3 0 Final Release 持久性 规范指出 一般来说 便携式应用程序不应调用 EntityManager 或查询操作 访问其他实体实例 或修改生命周期回调方法
  • 安装 Laravel 时出现错误:“./composer.json 不可写。”

    这是我运行的命令 composer global require laravel installer 这是我之后得到的文本和错误 Changed current directory to home dimitar composer comp
  • 使用 OpenCV 改进图像中的矩形轮廓检测

    我正在尝试检测给定图像中的矩形框 Original image but the image is not good enough to detect rectangles how can i improve it and detect al
  • Python 单元测试输出数据

    如果我用 Python 编写单元测试 使用 unittest 模块 是否可以输出失败测试的数据 以便我可以检查它以帮助推断导致错误的原因 我知道创建自定义消息的能力 它可以携带一些信息 但有时您可能会处理更复杂的数据 这些数据无法轻松表示为
  • 代号 1 个 JavaScript 回调

    我正在尝试在我的应用程序中显示同意页面 该页面应该用 html 编写 因此应用程序需要处理来自浏览器的按钮单击事件 我尝试复制博客中的例子 https www codenameone com blog new async java java
  • 如何将自定义图形适合boost图形库模板?

    我对 C 模板很生疏 而且我正在使用 boost 图形库 一个致命的组合 我在网上搜索过 但找不到任何关于如何采用自定义图形结构并将其足够适合 BGL 增强图形库 的直接说明 以便我可以使用增强图形遍历算法 有熟悉图书馆的人可以帮助我吗 编
  • 我可以更改 Firebug 控制台背景颜色吗?

    我更喜欢 Firebug 窗口具有深色背景颜色和浅色文本 或者甚至只是灰色背景而不是白色就足够了 有什么办法可以做到这一点 无论是通过调整 firebug 的原始文件还是通过使用扩展 这是一个不错的 firebug 深色主题 仅适用于 Fi
  • Visual Studio 错误:已添加具有相同键的项目

    当我尝试更改控件的默认图像时在 Windows 窗体上在表单设计器中 无论在哪个控件上的哪个位置 我收到此错误 错误消息 具有相同的项目 密钥已经添加 我尝试删除并重新创建资源 resx文件 我保证只有 1 个带有这些键的 resx 文件存
  • 在 PHP 8 上安装 apcu_bc 包时遇到问题

    安装包时遇到以下错误pecl install apcu bc在 PHP 8 上 In file included from tmp pear temp apcu bc php apc c 35 usr local include php e
  • 如何从滚动视图中删除子视图?

    我如何从滚动视图中删除所有子视图 我在滚动视图中有一个 uiview 和它上面的一个按钮 像这样 这是我在滚动视图中添加子视图的代码 void AddOneButton NSInteger myButtonTag lastButtonNum
  • java.util.regex.Pattern 可以进行部分匹配吗?

    是否可以知道流 字符串是否包含以下输入 could匹配正则表达式 例如 String input AA Pattern pat Pattern compile AAAAAB Matcher matcher pat matcher input
  • 按名称访问 ResourceDictionary

    假设我的 Application xaml 中有一些 ResourceDictionary 定义如下
  • django-reversion 撤消功能 - 恢复多个对象

    我正在尝试使用 django reversion 在 django 项目中实现 撤消 功能 以防用户意外修改多个对象 使用管理面板不起作用 因为必须一一恢复对象 我的问题是我无法创建包含多个对象数据的修订版本 即使当我这样做时 with r
  • React + Antd + Rollup 组件库“错误:无效的钩子调用。钩子只能在函数组件体内调用”

    我目前正在构建一个 UI 库来简化跨多个应用程序的维护 这些目前使用 Ant Design 一切似乎都很顺利 我在两者中都添加了我的对等依赖项package json and rollup config js 通过外部 我能够让 Rollu