首页 > 解决方案 > React Hook useEffect 缺少依赖项:'getData'。包括它或删除依赖数组

问题描述

我收到此错误 [React Hook useEffect 缺少依赖项:'getData'。包括它或删除依赖数组]请我解决这个问题..!

import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

const Phaltu = (props) => {
  const Id = props.match.params.gamename;
  // console.log(Id);
  const [value, setvalue] = useState([]);
  const getData = async () => {
    const res = await fetch(
      "http://51.143.173.5/api/developer/matchapi.php?Action=listCompetitions&EventTypeID=" +
        Id
    );
    const response = await res.json();
    setvalue(response);
    // console.log(response);
  };
  useEffect(() => {
    getData();
  }, []);
  return (
    <div>
      <ul>
        {value.map((currentElement, index) => {
          return (
            <li key={index}>
              <Link to={"/" + Id + "/" + currentElement.competition.id}>
                <p>{currentElement.competition.name}</p>
              </Link>
            </li>
          );
        })}
      </ul>
    </div>
  );
};

export default Phaltu;

标签: javascriptreactjs

解决方案


import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

const Phaltu = (props) => {
  const Id = props.match.params.gamename;
  // console.log(Id);
  const [value, setvalue] = useState([]);
 
  useEffect(() => {
 const getData = async () => {
    const res = await fetch(
      "http://51.143.173.5/api/developer/matchapi.php?Action=listCompetitions&EventTypeID=" +
        Id
    );
    const response = await res.json();
    setvalue(response);
    // console.log(response);
  };
    getData();
  }, []);
  return (
    <div>
      <ul>
        {value.map((currentElement, index) => {
          return (
            <li key={index}>
              <Link to={"/" + Id + "/" + currentElement.competition.id}>
                <p>{currentElement.competition.name}</p>
              </Link>
            </li>
          );
        })}
      </ul>
    </div>
  );
};

将函数声明移动到 useEffect 挂钩体内


推荐阅读