gpt4 book ai didi

node.js - npm-link 库上的无效 Hook 调用

转载 作者:行者123 更新时间:2023-12-04 00:53:55 31 4
gpt4 key购买 nike

问题描述:

  • 我目前正在创作一个名为 eformless 的包。
  • 我用过CRA创建一个名为 sandbox 的目录,我在哪里链接了包。
  • 在尝试使用我正在尝试测试的链接包启动沙盒 react 应用程序时,我不断收到以下错误:
    // inside my 'sandbox' App.tsx
    import React from 'react'
    import { useField } from 'eformless'

    const App = () => {
    const [test, handleChange] = useField('testing')
    return (
    <input type="text" value={test.value} onChange={handleChange} />
    )
    }

  • 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 appSee altered link due to stackoverflow ToS for tips about how to debug and fix this problem.

    出现问题的地方:
    这个问题似乎指向我的库,在那里我编写了一个自定义钩子(Hook),它使用从 React 导入的钩子(Hook)。
    这是我的代码中有问题的摘录:
    export const useField = <T>(
    input: T
    ...checkFunctions: Array<(...args: unknown[]) => unknown>
    ): [FieldType<T>, FieldHandlerFunction<T>, FieldHandlerFunction<T>] => {
    const [value, setValue] = useState(input)
    const [name, setName] = useState('')
    // Issue seems to be here ^
    }
    我的设置相当正常,似乎在其他项目中运行良好:
  • 首先,我通过 rollup -c 捆绑了我的库。
  • 在我的 eformless 中创建了一个链接库文件夹通过 npm link
  • 并在我的 sandbox 中创建了符号链接(symbolic link)文件夹通过 npm link eformless

  • 我尝试了什么:
    我自然地尝试通过错误消息中提供的链接解决问题。链接您自己的库时,这似乎是一个问题,如此处所述

    This problem can also come up when you use npm link or an equivalent. In that case, your bundler might “see” two Reacts — one in application folder and one in your library folder. Assuming myapp and mylib are sibling folders, one possible fix is to run npm link ../myapp/node_modules/react from mylib. This should make the library use the application’s React copy.


    我确实运行了 npm link ../sandbox/node_modules/react在我的 eformless文件夹,但这似乎没有帮助,即使在关闭 Node 服务器并重新编译之后也是如此。
    无论哪种方式,我都觉得很困惑,因为 runnign npm ls react只显示一个版本的 react ,它应该是有效的,给定 useState在自定义钩子(Hook)中使用顶层。
    重现问题
    两个存储库都是公开的
  • eformless library repo
  • sandbox repo
  • 最佳答案

    1. You might have more than one copy of React in the same app See altered link due to stackoverflow ToS for tips about how to debug and fix this problem.

    这是因为您在 devDependencies 中做出了 react 为无形。这会导致您的应用程序运行两个 React 实例。
    取而代之的是,在无形的 package.json 中对对等依赖项使用react,删除您的 node_modules目录并运行 npm install .
    通过添加对对等依赖项的 react ,您通知您的模块捆绑器不要包含 react ,而是期望 react 将由依赖的应用程序提供给它。
    "peerDependencies": {
    "react": "^16.13.1"
    }
    另外,我注意到您已 checkin 您的 node_modules。目录变成无形的。你不应该那样做。相反,添加 node_modules给您的 .gitignore文件。

    关于node.js - npm-link 库上的无效 Hook 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64283813/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com