错误 :: 无效的挂钩调用。 Hooks 只能在函数组件内部调用

时间:2021-03-23 11:59:57

标签: javascript reactjs react-redux lerna

我正在尝试使用 microbundle

捆绑我的自定义组件

参考https://github.com/developit/microbundle 我的组件 package.json 是这个。

{
  "name": "components",
  "version": "0.0.0",
  "description": "react.js component library",
  "homepage": "",
  "license": "ISC",
  "main": "dist/index.js",
  "source": "lib/index.js",
  "directories": {
    "lib": "lib",
    "test": "__tests__"
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "dev": "microbundle --external=\"react,react-dom\" --globals=\"React,ReactDOM\" watch --jsx React.createElement lib/*.js"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "prop-types": "^15.7.2",
    "react-debounce-input": "^3.2.3"
  },
  "devDependencies": {
    "microbundle": "^0.13.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  },
  "peerDependencies": {
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  }
}

当我有这个组件时

import React from 'react';
const Index = () => {
    return (
        <div>
            <button onClick={()=>{
                alert('==')
            }}>{'state'}</button>
        </div>
    );
};

export default Index;

它完美运行。我在 NEXTJS 或(服务器端反应框架)中使用这个组件。

但是当我使用 HOOKS 时,它会显示以下错误

import React from 'react';
const Index = () => {
     const [state,setState] = React.useState(0)
    return (
        <div>
            <button onClick={()=>{
                alert('==')
            }}>{'state'}</button>
        </div>
    );
};

export default Index;

错误

我的 bundle.js

function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var t=e(require("react"));exports.Header=function(){return t.default.useState(0),t.default.createElement("div",null,t.default.createElement("button",{onClick:function(){alert("==")}},"state"))};
//# sourceMappingURL=index.js.map

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以尝试删除 .next 文件夹并再次运行服务器。