簡體   English   中英

react js中的無效掛鈎調用錯誤,如何在類組件中使用useState?

[英]Invalid Hook Call Error in react js, how can I use useState in class component?

我想使用類組件,但它會出錯。

我知道代碼打破了 Hooks 的規則

我想知道如何在類組件中使用 useState?

我將在父組件中使用這個組件,所以我必須使用類組件

我不知道什么是最好的方法請幫助我

import axios from 'axios';
import React, { createElement, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

class Portfolio extends React.Component {
  render() {
    const [skill, setSkill] = useState([]);
    const [career, setCareer] = useState([]);
    const [education, setEducation] = useState([]);
    const [project, setProject] = useState([]);
    const [etcEducation, setEtcEducation] = useState([]);
    const [language, setLanguage] = useState([]);
    const [certificate, setCertificate] = useState([]);
    const [award, setAward] = useState([]);
    const [introduce, setIntroduce] = useState([]);

    const getToken = localStorage.getItem('token');
    const getUserIdx = localStorage.getItem('userIdx');
    const { portfolio_idx } = useParams();

    const [userInfo, setUserInfo] = useState([]);

    // user 정보 get
    const getUserInfo = () => {
      axios
        .get(`http://localhost:3001/users/${getUserIdx}`, {
          headers: {
            authorization: getToken,
          },
        })
        .then((res) => {
          const userData = res.data.data;
          setUserInfo(userData);
        })
        .catch((err) => console.log(err));
    };

    // portfolio get
    const getPortfolio = () => {
      axios
        .get(`http://localhost:3001/portfolios/${portfolio_idx}`)
        .then((res) => {
          const datas = res.data.data;
          setSkill(datas.skill);
          setCareer(datas.career);
          setEducation(datas.education);
          setProject(datas.website);
          setLanguage(datas.language);
          setCertificate(datas.certificate);
          setEtcEducation(datas.etc_education);
          setAward(datas.award);
          setIntroduce(datas.introduce);
        })
        .catch((err) => console.log(err, '실패'));
    };

    useEffect(() => {
      getUserInfo();
      getPortfolio();
    }, []);
    
    return (
        ) : null}
      </div>
    );
  }
}

export default Portfolio;

不能在類組件中使用useState

這是具有狀態的類組件的示例示例。

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

在這里你可以看到tick()正在使用this.setState() 您可以在CLASS COMPONENTS中修改您的狀態

暫無
暫無

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

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