带有 hooks 的 React 组件作为 npm 模块

Twi*_*ist 6 npm reactjs npm-publish react-hooks

当我尝试在用作依赖项的模块中使用 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:
Run Code Online (Sandbox Code Playgroud)

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

这是我的摘录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"
  }
}
Run Code Online (Sandbox Code Playgroud)

这是该组件:

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

Gir*_*tto 1

也许您尝试使用的是useState而不是useEffect

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