接收错误:功能组件中的无效钩子调用

时间:2020-06-02 20:19:10

标签: javascript reactjs react-hooks

我正在尝试创建一个简单的组件并将其发布到npm。在发布之前,我想测试一下该组件。但是,每当我在测试应用程序中使用组件时,都会得到以下信息:Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

这是有问题的组件:

MyComponent.tsx:

import React, { useState } from 'react';

const MyComponent = () => {
  const [count, setCount] = useState(0);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return (
    <div>
      <pre></pre>
      <button onClick={increment} name='test1'>
        Increment
      </button>
      <button onClick={decrement} name='test2'>
        Decrement
      </button>
    </div>
  );
};

export default MyComponent;

index.ts:

import MyComponent from './MyComponent';

import './index.css';

export { MyComponent };

这是测试应用程序:

import React from 'react';
import './App.css';
import { MyComponent } from 'one-select';

function App() {
  return (
    <div className="App">
      <div>
        <MyComponent />
      </div>
    </div>
  );
}

export default App;

MyComponent通过npm install /path/to/mycomponent-project导入测试应用

我之前已经创建了其他React应用(但不是独立组件),而且从来没有这个问题。任何建议将不胜感激。

0 个答案:

没有答案