reactjs - React 库中的 React hooks 给出无效的 hook 调用错误

标签 reactjs react-router-dom react-hooks

我使用 https://www.npmjs.com/package/create-react-library 创建一个 react 库 并在其他React项目上成功使用。 但是当我尝试在库内使用 React hooks 功能时,它给出了以下错误。

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
.....

我的图书馆 我只是尝试在我的组件中使用 useState ,如下所示。

import React, { useState } from 'react'

const General = (props) => {

    const [count, setCount] = useState(0);
    return (
        <div>
           General component
        </div>
    )
}

export default General

我正在使用 "react": "^16.8.6""react-dom": "^16.8.6"

我的 React 应用 使用https://github.com/facebook/create-react-app创建了一个应用程序并按如下方式使用上述库。

import Reactfrom 'react'
import { General } from 'my.lib'
const accountSummary = props => {

  return (
    <div>
      <General>
    </div>
  )
}

export default accountSummary

两者都有相同的react版本,并且库使用了与peerDependencies相同的react-dom和react版本

最佳答案

我在我的应用程序中包含了我的组件库(就此而言,任何库),就像 @Janith 使用 my-comp-lib:"file:../.." (我不不想每次我想测试时都发布)并且我遇到了同样的问题。

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 react-invalid-hook-call for tips about how to debug and

fix this problem

我可以通过让我的应用程序和库指向相同的 react (包)位置来解决这个问题。

Below are the steps I followed :
1. In Your Application:
a) cd node_modules/react && npm link
b) cd node_modules/react-dom && npm link

2. In Your Library
a) npm link react
b) npm link react-dom

3)Stop your dev-server and do `npm start` again.

它有效!!

请参阅以下链接了解更多详细信息..

https://github.com/facebook/react/issues/14721

https://github.com/facebook/react/pull/14690

https://github.com/facebook/react/issues/13991

注意:如果您将包发布到artifactory并安装,则不会发生此问题,因为您将react和react-dom作为对等依赖项,并且它们不会包含在发行版中。因此,您的包和应用程序使用应用程序中安装的相同的 React。

关于reactjs - React 库中的 React hooks 给出无效的 hook 调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56021112/

相关文章:

html - 如何在reactjs中渲染完整的html

reactjs - 后退按钮在 React 中显示空白页面

reactjs - react 路由器dom重定向问题。更改 url,不呈现组件

reactjs - react : HashRouter Not Reloading Page on Electron

javascript - 从钩子(Hook)返回值(value) promise

javascript - 如何在 React useEffect hook 中获取更新的状态值

javascript - React useCallback 设置对回调内调用的函数的依赖

reactjs - 有没有办法告诉 React/Redux 文件结构中*哪里*调用了一个操作?

javascript - React - 在获取数据后设置状态时渲染 HTML

reactjs - React 中未设置 useState