簡體   English   中英

錯誤“無法在 class 組件中調用 React Hook "useState"”的解決方案是什么

[英]What is the solution to the error 'React Hook "useState" cannot be called in a class component'

首先,我查看了stackoverflow上的所有答案,但仍然出現錯誤。

在下面的代碼中,我在 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;

你能幫我解決這個問題嗎? 我該如何解決這種情況?

在此處輸入圖像描述

將 state 用於 function 組件,您不能在 class 組件中使用

解決方案是使用 function 組件而不是 class 組件,如錯誤所示:D。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM