[英]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 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. 挂钩是一项即将推出的功能,可让您无需编写类即可使用状态和其他React功能。 They're currently in React v16.8.0-alpha.0. 他们目前在React v16.8.0-alpha.0中。
Please check react version as the hook methods works with v16.8.0 . 请检查react版本,因为hook方法适用于v16.8.0。
Hope this helps, 希望这可以帮助,
Cheers !! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.