我正在尝试使用 react Hook 导出正常的功能组件,但收到此错误。
TypeError: Object(...) is not a function
当我删除钩子(Hook)并将其导出时没有任何状态它可以工作。导出相同的代码作为类组件也可以。
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...
这就是问题所在。 v16.8 中添加了 Hook,因此代码中的 useState
是 undefined
。
(这是转译向您隐藏错误的情况之一[并不是说如果您需要支持较旧的环境,您有很多选择]。如果那是 native import
语句,那么它将会失败,并出现一个有用的错误,指出 React 没有 useState
命名导出。但是当使用 CJS 或 AMD 版本的 React 时,您的代码会转换为执行 var useState = 的操作React.useState;
所以它不会出错,它只是给你 undefined
- 这不是一个函数。:-) )
关于javascript - 使用钩子(Hook)时,reactjs TypeError : Object(. ..) 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495030/