reactjs TypeError: Object(...) is not a function when using hooks

reactjs TypeError: Object(...) is not a function when using hooks

我正在尝试使用反应钩子导出一个正常的功能组件,但我收到了这个错误。

TypeError: Object(...) is not a function

当我移除挂钩并在没有任何状态的情况下导出它时,它可以正常工作。将相同的代码导出为 Class 组件也可以。

import React,{ useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Mycomponent;

这是我导入和使用功能组件的方式。

import Mycomponent from './mycomponet';
class MYClassComponent extends Component {
  render() {
    return (
      <Mycomponent />
    }
}

我正在使用 react 16.6.3 并使用 create-react-app

I am using react 16.6.3...

这就是问题所在。 hooks 是在 v16.8 中添加的,所以你代码中的 useStateundefined.

(这是转译对您隐藏错误的那些时候之一 [并不是说如果您需要支持旧环境,您有很多选择]。如果那是原生的 import 语句,它会失败并显示一个有用的错误,指出 React 没有 useState 命名导出。但是当使用 CJS 或 AMD 版本的 React 时,您的代码会转换为执行 var useState = React.useState; 的内容,因此它不会”不会出错,它只会给你 undefined——这不是一个函数。:-))