【问题标题】:What is the solution to the error 'React Hook "useState" cannot be called in a class component'错误\'React Hook \"useState\" cannot be called in a class component\'的解决方法是什么
【发布时间】:2022-09-25 23:32:33
【问题描述】:

首先,我查看了所有的答案堆栈溢出但我仍然得到错误。

在下面的代码中,我在 Render 中调用 JSON,并将其添加到选项卡中。我尝试了许多不同的方法,但无法弄清楚。

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;

你能帮我解决这个问题吗?我该如何解决这种情况?

  • 它从字面上告诉你问题是什么。你不能在类组件中使用钩子。
  • 它从字面上告诉你问题是什么。你不能在类组件中使用钩子。

标签: reactjs react-hooks


【解决方案1】:

对不能在类组件中使用的功能组件使用状态

【讨论】:

    猜你喜欢
    • 2022-12-22
    • 2023-02-16
    • 2021-08-24
    • 2023-02-08
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    相关资源
    最近更新 更多