4

我正在使用 Yarn v2 (berry) 来管理具有以下结构的 monorepo:

project-root
  /packages
    react-native-app
      (dependencies: my-hooks-lib, react@17.0.1)
    my-hooks-lib
      (dependency: react@17.0.1)

这是我的 .yarnrc.yml:

yarnPath: ".yarn/releases/yarn-berry.cjs"
nodeLinker: "node-modules"
nmHoistingLimits: "workspaces"

自从我使用 React Native 应用程序以来,我已经禁用了提升。但正因为如此,react-native-app并且my-hooks-lib有单独的副本react@17.0.1,即使版本相同。这会导致Invalid Hooks call错误:

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.

这是因为my-hooks-lib使用了不同的 React 副本,即使版本相同。如果我像这样导入 React,它工作正常:

// inside my-hooks-lib
import React from "../react-native-app/node_modules/react";

我让 React 成为对等依赖 inside my-hooks-lib,但这也没有帮助,因为 Yarn 创建了一个到my-hooks-libinside的符号链接react-native-app,但它无法解析 React。然后,我将 React 作为开发依赖项安装在项目的根目录下,现在我回到原来的问题,因为现在my-hooks-lib指的是项目根目录下的 React 副本。

有没有办法在开发过程中解决这个问题?


更新:作为一种解决方法,我将 React 作为和的对等依赖项react-native-appmy-hooks-lib并在项目根目录中添加 React 作为开发依赖项。所以这就是它现在的样子:

<project-root>
  (dev-dependency: react@17.0.1)
  /packages
    /react-native-app
      (dependency: my-hooks-lib, peer-dependency: react@17.0.1)
    /my-hooks-lib
      (peer-dependency: react@17.0.1)

虽然我仍然很想听到更好的解决方案!

4

0 回答 0