使用钩子作为npm模块来反应组件

时间:2019-10-11 14:17:56

标签: reactjs npm react-hooks npm-publish

当我尝试在用作依赖项的模块中使用React Hooks时,它失败了。 我遇到以下错误:

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:

但是如果我使用基于类的组件,那就可以了。为什么会发生这种情况?

这是我的package.json的摘录

{
  "main": "dist/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "./node_modules/.bin/babel src -d dist",
    "prepublish": "npm run build"
  },
  "peerDependencies": {
    "react": "^16.10.2",
    "react-router-dom": "^5.1.2"
  },
  "devDependencies": {
    "axios": "^0.19.0",
    "jwt-decode": "^2.2.0",
    "qs": "^6.9.0",
    "@babel/cli": "^7.6.4",
    "@babel/core": "^7.6.4",
    "@babel/preset-env": "^7.6.3",
    "@babel/preset-react": "^7.6.3"
  }
}

以下是组件:

const Test = () => {
  const [state, setState] = React.useState('test')
  return <div>{state}</div>
}

2 个答案:

答案 0 :(得分:1)

也许您要使用的是 useState ,而不是 useEffect

const Test = () => {
  const [state, setState] = React.useState('test')
  return (<div>{state}</div>)
 }

答案 1 :(得分:0)

您无法创建带有钩子的npm库,您需要将钩子转换为类组件并将其转换为库