React Hook useEffect 缺少依赖项:'getData'。包括它或删除依赖数组[重复]
Posted
技术标签:
【中文标题】React Hook useEffect 缺少依赖项:\'getData\'。包括它或删除依赖数组[重复]【英文标题】: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
在同一个作用域内声明
【参考方案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挂钩体中
【讨论】:
以上是关于React Hook useEffect 缺少依赖项:'getData'。包括它或删除依赖数组[重复]的主要内容,如果未能解决你的问题,请参考以下文章
React Hook useEffect 缺少依赖项:'props' 由于 useEffect 中有一行
React Hook useEffect 缺少依赖项(没有在 useEffect 中移动函数)
反应 | React Hook useEffect 缺少依赖项