React 钩子重复的 React 包 [英] React hooks duplicate react package

查看:47
本文介绍了React 钩子重复的 React 包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处所述,在反应库中使用钩子时,经常会遇到反应错误说 hooks 只能在函数组件的主体内调用导致此错误的最可能原因是您的库链接到其自己的 React 包以及您的主应用程序,因此您最终使用了 2 个不同的 React 包副本.

As described here, when using hooks in a react library, you often encounter a react error saying hooks can only be called inside the body of a function component The most likely cause for this error is that your library links to its own react package and you main app also, so you end up using 2 different copies of the react package.

此错误的一个典型解决方案是确保您的主应用程序和您的库使用完全相同的 React 包.

One typical solution to this error is to make sure you main app AND your library use the exact same react package.

我使用的解决方案是:

  • cd 到 myMainApp/node_modules/react
  • 纱线链接
  • cd 到 myLib
  • yarn link react

此解决方案有效.我的主应用程序和我的库现在使用相同的 React 包.

This solution works. My main app and my library now use the same react package.

但是如果我有多个主要应用怎么办?假设我有这个项目结构:

But what if I have multiple main apps? Let's say I have this project structure:

mainApp1 使用 lib1-1 和 lib1-2

mainApp1 using lib1-1 and lib1-2

mainApp2 使用 lib2-1 和 lib2-2

mainApp2 using lib2-1 and lib2-2

两个主要应用程序相互独立.所以lib1-1和lib1-2应该链接到mainApp1的react包,lib2-1和lib2-2都应该链接到mainApp2的react包

Both main apps are independent of each other. So lib1-1 and lib1-2 should link to the react package of mainApp1 and lib2-1 and lib2-2 should both link to the react package of mainApp2

我该怎么做?当我尝试在 mainApp2/node_modules/react 中运行 yarn link 时,yarn 告诉我已经有一个用于 react 的链接.

How do I do that? When I try to run yarn link in mainApp2/node_modules/react, yarn tells me that there is already a link for react.

不幸的是,我不能使用 yarn link as react2 或类似的东西.

Unfortunately, I cannot use yarn link as react2 or something similar.

关于如何克服这个问题有什么想法吗?

Any ideas on how to overcome this?

注意:这个问题可以通过构建你的库(其中 react 是一个 devDependency)来解决,在每次调整后将你的更改提交到 git,然后在你的主应用程序中升级库.但是当然,这不是解决方案,因为在开发过程中,您希望链接到您的库,而不是从存储库中重新导入它们

Note: this problem can be overcome by building your library (where react is a devDependency), committing your changes to git after every tweak and than upgrade the library in your main app. But off course, this is not a solution since during developing, you want to link to you libraries instead of re-importing them from the repo's

推荐答案

您可以全局安装 react 和 react-dom,然后将您的所有项目链接到全局实例.

You can install react and react-dom globally, then link all of your projects to the global instance.

该过程与您已经使用的过程类似,但会创建指向全局位置的符号链接:

The procedure would be similar to the one you're using already, but creating symlinks to the global locations:

yarn global add react
yarn global add react-dom

然后您可以从您的个人项目链接到它们.

Then you can link to them from your individual projects.

这篇关于React 钩子重复的 React 包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆