繁体   English   中英

反应| 功能组件抛出错误useState Object(…)不是函数

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

我正在尝试根据本文创建一个组件:

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

但是,仅从上面的链接复制粘贴功能组件会引发错误:

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');

完整的组件代码:

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;

挂钩是一项即将推出的功能,可让您无需编写类即可使用状态和其他React功能。 他们目前在React v16.8.0-alpha.0中。

请检查react版本,因为hook方法适用于v16.8.0。

希望这可以帮助,

干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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