简体   繁体   中英

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

I am trying to export a normal functional component using the react hooks but I am getting this error.

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

when I remove the hooks and export it without any states it works. Exporting the same code as a Class component also works.

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;

here is how I am importing and using functional component.

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

I am using react 16.6.3 and used create-react-app .

I am using react 16.6.3...

That's the problem. Hooks were added in v16.8, so useState in your code is undefined .

(This is one of those times that transpiling hid the error from you [not that you have much choice if you need to support older environments]. If that had been a native import statement, it would have failed with a useful error saying that React didn't have a useState named export. But when using a CJS or AMD version of React, your code gets converted to something doing var useState = React.useState; and so it doesn't error out, it just gives you undefined — which isn't a function. :-) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM