V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
coderabbit
V2EX  ›  React

react hook 组件 webpack 打包后不能使用

  •  
  •   coderabbit · 2020-03-10 10:15:16 +08:00 · 3551 次点击
    这是一个创建于 1480 天前的主题,其中的信息可能已经有所发展或是发生改变。

    用 hook 写的组件,打包后在别的项目使用,然后报!

    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
    

    然后我把 hook 里的 useState useRef 去掉就一个纯函数式组件。打包后再引用没问题!然后我又把组件直接放在项目里使用没有问题,唯独我组件中使用了 useState 打包引用就会报上面的错!还是说 hook 组件是不能用 webpack 打包发布的?

    8 条回复    2020-03-10 21:13:35 +08:00
    Yumwey
        1
    Yumwey  
       2020-03-10 10:18:03 +08:00
    重新 install react 包试试。
    motoude
        2
    motoude  
       2020-03-10 10:20:54 +08:00
    别的项目版本是多少是否>=16.8
    coderabbit
        3
    coderabbit  
    OP
       2020-03-10 10:24:26 +08:00
    @motoude 两边都是最新的 16.13
    KuroNekoFan
        4
    KuroNekoFan  
       2020-03-10 11:01:24 +08:00
    感觉你得直接上代码网友才能看出点东西
    otakustay
        5
    otakustay  
       2020-03-10 11:02:22 +08:00
    应该是打了 2 份 react 进去的关系,用 alias 把所有 react 指到一个东西上面吧
    ZZITE
        6
    ZZITE  
       2020-03-10 11:31:32 +08:00
    多个 react 包的问题吧,看下这个 https://github.com/facebook/react/issues/13991
    lizz666
        7
    lizz666  
       2020-03-10 14:43:48 +08:00
    赞同楼上,估计是多个 react 包问题,我之前发布组建也有这种问题,我的踩坑记录: https://github.com/lizhongzhen11/dailyGain/issues/57
    coderabbit
        8
    coderabbit  
    OP
       2020-03-10 21:13:35 +08:00   ❤️ 1
    @ZZITE @lizz666 谢谢解决了!
    ```
    externals: {
    'react': 'React',
    'react-dom': 'ReactDOM',
    'react-router-dom': 'ReactRouterDOM'
    }
    ```
    之前我是这样排除的。我发现包里确实没有打包进去这些东西。后面看了 issues
    ```
    react: {
    root: 'React',
    commonjs2: 'react',
    commonjs: 'react',
    amd: 'react'
    },
    'react-dom': {
    root: 'ReactDOM',
    commonjs2: 'react-dom',
    commonjs: 'react-dom',
    amd: 'react-dom'
    },
    'react-router-dom': {
    root: 'ReactRouterDOM',
    commonjs2: 'react-router-dom',
    commonjs: 'react-router-dom',
    amd: 'react-router-dom'
    }
    ```
    这样打包后项目引用没报错了!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2912 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 14:15 · PVG 22:15 · LAX 07:15 · JFK 10:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.