如何解决“React Hook useEffect 缺少依赖项。包含它或删除依赖项数组”问题?

Sam*_*man 6 typescript reactjs react-redux react-hooks react-typescript

我想使用useEffect,但是当我添加getUpperGroup方法时,我收到警告:

React Hook useEffect 缺少依赖项:'getUpperGroups'。包括它或删除依赖数组”

我的代码是:

useEffect(() => {
  getUpperGroups();
  setContentData(contentGroupData);
}, [contentGroupData]);


const [contentData, setContentData] = useState<Fundation[]>([] as Fundation[]);
const [upperGroups, setUpperGroups] = useState({});

const getUpperGroups = () => {

   let newUpperGroups = upperGroups;

   contentGroupData.forEach(content=>{
     newUpperGroups = {...newUpperGroups, [content.id]: content.title};
   })

   setUpperGroups(newUpperGroups);
}
Run Code Online (Sandbox Code Playgroud)

Hos*_*adi 10

你有两个错误。

1-您在useEffect之后定义了getUpperGroups,因此您无法将其添加到useEffect依赖项列表中。

2-如果您将 getUpperGroups 添加到 useEffect 依赖项列表中,则 useEffect 将在每次重新渲染时运行,并且您会给出一个重新渲染错误循环。

所以有两种解决方案。

1-将 getUpperGroups 添加到 useEffect 中

const [contentData, setContentData] = useState<Fundation[]>([] as Fundation[]);
const [upperGroups, setUpperGroups] = useState({});


useEffect(() => {
  
  const getUpperGroups = () => {

   let newUpperGroups = upperGroups;

   contentGroupData.forEach(content=>{
     newUpperGroups = {...newUpperGroups, [content.id]: content.title};
   })

   setUpperGroups(newUpperGroups);
  }

  getUpperGroups();
}, [contentGroupData]);

Run Code Online (Sandbox Code Playgroud)

2-禁用eslint

useEffect(() => {
  getUpperGroups();
  setContentData(contentGroupData);

  // eslint-disable-line react-hooks/exhaustive-deps
}, [contentGroupData]);


const [contentData, setContentData] = useState<Fundation[]>([] as Fundation[]);
const [upperGroups, setUpperGroups] = useState({});

const getUpperGroups = () => {

   let newUpperGroups = upperGroups;

   contentGroupData.forEach(content=>{
     newUpperGroups = {...newUpperGroups, [content.id]: content.title};
   })

   setUpperGroups(newUpperGroups);
}
Run Code Online (Sandbox Code Playgroud)