[英]What is the solution to the error 'React Hook "useState" cannot be called in a class component'
first of all I have looked at all the answers on stackoverflow but I still get the error.首先,我查看了stackoverflow上的所有答案,但仍然出现错误。
In the code below, I call the JSON in Render and I want to add it to the tab.在下面的代码中,我在 Render 中调用 JSON 并将其添加到选项卡中。 I tried many different ways but couldn't figure it out.
我尝试了许多不同的方法,但无法弄清楚。
import React, { useState, useEffect } from 'react';
import classnames from "classnames";
// reactstrap components
import {
Card,
CardBody,
NavItem,
NavLink,
Nav,
TabContent,
TabPane,
Row,
Col
} from "reactstrap";
class Devices extends React.Component {
state = {
iconTabs: 1,
plainTabs: 1
};
toggleNavs = (e, state, index) => {
e.preventDefault();
this.setState({
[state]: index
});
};
render() {
const [data, getData] = useState([{}])
const URL = 'API_URL';
useEffect(() => {
fetchData()
}, [])
const fetchData = () => {
fetch(URL)
.then((res) =>
res.json())
.then((response) => {
console.log(response);
getData(response);
})
}
return (
<>
<Card className="shadow">
<CardBody>
<TabContent activeTab={"iconTabs" + this.state.iconTabs}>
<TabPane tabId="iconTabs1">
<p className="description">
{data.map((item, i) => (
<p>{item.description}</p>
))}
</p>
</TabPane>
</CardBody>
</Card>
</Col>
</Row>
</>
);
}
}
export default Devices;
Can you help me with this?你能帮我解决这个问题吗? How can I solve this situation?
我该如何解决这种情况?
use state for function components you can't used in class components将 state 用于 function 组件,您不能在 class 组件中使用
The solution is to use function components instead of class components, as the error says:D.解决方案是使用 function 组件而不是 class 组件,如错误所示:D。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.