Jan*_*ana 4 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
.....
Run Code Online (Sandbox Code Playgroud)
我的图书馆 我只是尝试在组件中使用useState,如下所示。
import React, { useState } from 'react'
const General = (props) => {
const [count, setCount] = useState(0);
return (
<div>
General component
</div>
)
}
export default General
Run Code Online (Sandbox Code Playgroud)
我正在使用
"react": "^16.8.6"和 "react-dom": "^16.8.6"
我的React APP 使用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
Run Code Online (Sandbox Code Playgroud)
两者具有相同的反应版本,并且库使用与以下相同的react-dom和react版本 peerDependencies
我刚刚遇到了同样的问题。我能够通过在示例应用程序中指向与库中相同的反应来修复它:
应用程序结构
根
因此,从 example > package.json 我将反应更改为:
"react": "link:../node_modules/react",
Run Code Online (Sandbox Code Playgroud)
这与npm link上面列出的非常相似,但每次 npm 安装时它都不会消失。
我遇到了同样的问题,使用 rush monorepo,配置 ui-package 并使用 nextjs 构建应用程序。
解决方案是添加以下代码package.json
"resolutions": {
"react": "17.0.1", // verificate your react version
"react-dom": "17.0.1"
}
Run Code Online (Sandbox Code Playgroud)
在图书馆的package.json:
"peerDependencies": {
"react": "17.0.1",
"react-dom": "17.0.1"
},
Run Code Online (Sandbox Code Playgroud)
在此处查看更多信息:https://github.com/vercel/next.js/issues/9022#issuecomment-728688452
我像@Janith那样使用了我的组件库(就此而言,任何库都包括在我的应用程序中)my-comp-lib:"file:../.."(我不想每次都想测试都发布),并且遇到了相同的问题。
无效的挂接调用。挂钩只能在功能组件的主体内部调用。可能由于以下原因之一而发生:
- 您可能使用了不匹配的React和渲染器版本(例如React DOM)
- 您可能正在违反挂钩规则
- 您可能在同一应用程序中拥有多个React副本。有关如何调试和调试的提示,请参见react-invalid-hook-call。
解决这个问题
我可以通过使我的应用程序和库指向相同的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.
Run Code Online (Sandbox Code Playgroud)
有用!!
请参考以下链接以获取更多详细信息..
https://github.com/facebook/react/issues/14721
https://github.com/facebook/react/pull/14690
https://github.com/facebook/react/issues/13991
注意:如果您将软件包发布到工件并安装,则不会发生此问题,因为您将具有react&react-dom作为对等依赖性,并且它们不会包含在分发中。因此,您的程序包和应用程序使用与应用程序中安装的相同的React。
| 归档时间: |
|
| 查看次数: |
1452 次 |
| 最近记录: |