【问题标题】:React Hook useEffect has a missing dependency: 'getData'. Either include it or remove the dependency array [duplicate]React Hook useEffect 缺少依赖项:'getData'。包括它或删除依赖数组[重复]
【发布时间】:2021-08-24 08:27:26
【问题描述】:

我收到此错误 [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;

【问题讨论】:

  • 将 getData 函数移到 useEffect 函数中。
  • 应该和useEffect在同一个作用域内声明

标签: javascript reactjs


【解决方案1】:
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挂钩体中

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 2020-07-19
    • 2020-05-31
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2021-09-10
    • 2020-09-26
    • 2021-08-26
    相关资源
    最近更新 更多