【问题标题】:Using Material UI is causing invalid hook call warning使用 Material UI 导致无效的钩子调用警告
【发布时间】:2019-08-10 09:36:29
【问题描述】:

我正在尝试create-react-library 捆绑一个可重用的库。我正在尝试的想法是创建可组合的组件库,我们可以在我们的网络应用和电子应用中使用。

在我们的 package.json 文件中,我们有以下要求

"peerDependencies": {
    "react": "^15.0.0 || ^16.0.0",
    "react-dom": "^15.0.0 || ^16.0.0"
},
"devDependencies": {
    "@material-ui/core": "^4.0.0-alpha.4",
    ....
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
}

当我导入 Material UI 组件时,它会导致错误

Hooks 只能在函数组件内部调用。 https://reactjs.org/warnings/invalid-hook-call-warning.html

这是完整的组件(它只是我正在慢慢扩展的 create-react-library 中的示例)

import React, { Component } from 'react'
import PropTypes from 'prop-types'

import { Button } from "@material-ui/core";

import styles from './styles.css'

class ExampleComponent extends Component {
  static propTypes = {
    text: PropTypes.string
  }

  render() {
    const { text } = this.props

    return (

        <div className="">
          <Button></Button>
          Example Component: {text}
        </div>
    )
  }
}

export default ExampleComponent;

************************************ 编辑 ************ ************************

更改材质 ui 和 react 的 devDependencies 并添加到 rollup.config.js 文件(以处理由此引入的问题)修复了错误

"devDependencies": {
    "@material-ui/core": "^3.9.0",
    ...
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
   }

rollup.config.js

commonjs({
  include: 'node_modules/**',
  namedExports: {
    'node_modules/@material-ui/core/styles/index.js': [
      'createGenerateClassName',
      'createMuiTheme',
      'createStyles',
      'jssPreset',
      'MuiThemeProvider',
      'withStyles',
      'withTheme'
    ],
    'node_modules/@material-ui/core/Modal/index.js': [ 'ModalManager' ]
  }
})

【问题讨论】:

  • 错误信息本身不完整。您是否查看了链接并尝试在文章的帮助下调试问题?
  • 不确定您所说的“不完整”是什么意思;错误消息包含在票证中,与我看到的完全一样。是的,我已经尝试过调试了。
  • 我的意思是说反应正在控制台中显示。你读过这篇文章吗:reactjs.org/warnings/invalid-hook-call-warning.html
  • @epsilon ...是的。我回答了你的第一条评论,说我读了这篇文章。如果没有先做研究,我不会在 stackoverflow 上发帖。
  • @epsilon islalobo 的主要变化是将 Material-Ui 从 alpha 版本降级为 ^3.9.0,因此在 16.7 中应该可以进行反应。

标签: reactjs material-ui react-hooks rollupjs


【解决方案1】:

在我的例子中,我安装了一个带有 node_modules 文件夹的子模块,我实际上是在将 react 两次编译成一个包。

已通过删除子模块的 node_modules 文件夹修复,也可能在 webpack 配置中修复:

   main
      node_modules
      submodules
          -> node_modules

【讨论】:

    猜你喜欢
    • 2019-12-06
    • 2021-09-10
    • 2022-01-24
    • 2021-08-04
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多