简体   繁体   中英

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.

In the code below, I call the JSON in Render and I want to add it to the tab. 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

The solution is to use function components instead of class components, as the error says:D.

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