简体   繁体   中英

React | Functional component throws error useState Object(…) is not a function

I am trying to create a component based on this article:

https://scotch.io/tutorials/5-ways-to-convert-react-class-components-to-functional-components-w-react-hooks#toc-class-with-state-and-componentdidmount

But simply copy pasting the functional component from the above link throws an error:

TypeError: Object(...) is not a function
Home
src/components/Home.js:3
  1 | import React, { useState, useEffect } from 'react';
  2 | 
> 3 | function Home() {
  4 | 
  5 |   const [userName, setUsername] = useState('JD');
  6 |   const [firstName, setFirstname] = useState('John');

Full component code:

import React, { useState, useEffect } from 'react';

function Home() {

  const [userName, setUsername] = useState('JD');
  const [firstName, setFirstname] = useState('John');
  const [lastName, setLastname] = useState('Doe');

  useEffect(() => {
    setInterval(() => {
      setUsername('MJ');
      setFirstname('Mary');
      setLastname('Jane');
    }, 5000);
  });

  const logName = () => {
    // do whatever with the names ...
    console.log(this.state.userName);
    console.log(this.state.firstName);
    console.log(this.state.lastName);
  };

  const handleUserNameInput = e => {
    setUsername({ userName: e.target.value });
  };
  const handleFirstNameInput = e => {
    setFirstname({ firstName: e.target.value });
  };
  const handleLastNameInput = e => {
    setLastname({ lastName: e.target.value });
  };

  return (
    <div>
      <h3> The text fields will update in 5 seconds </h3>
      <input
        type="text"
        onChange={handleUserNameInput}
        value={userName}
        placeholder="Your username"
      />
      <input
        type="text"
        onChange={handleFirstNameInput}
        value={firstName}
        placeholder="Your firstname"
      />
      <input
        type="text"
        onChange={handleLastNameInput}
        value={lastName}
        placeholder="Your lastname"
      />
      <button className="btn btn-large right" onClick={logName}>
        {' '}
        Log Names{' '}
      </button>
    </div>
  );
};

export default Home;

Hooks are an upcoming feature that lets you use state and other React features without writing a class. They're currently in React v16.8.0-alpha.0.

Please check react version as the hook methods works with v16.8.0 .

Hope this helps,

Cheers !!

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