React Hook useEffect 缺少依赖项:[重复]

Posted

技术标签:

【中文标题】React Hook useEffect 缺少依赖项:[重复]【英文标题】:React Hook useEffect has a missing dependency: [duplicate] 【发布时间】:2021-10-16 01:35:24 【问题描述】:

我正在构建一个带有 react 的 webapp,我收到了这个警告:

src\Containers\App.js
  Line 30:6:  React Hook useEffect has a missing dependency: 'API_KEY'. Either include it or remove the dependency array  react-hooks/exhaustive-deps
  Line 36:6:  React Hook useEffect has a missing dependency: 'API_KEY'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

这里是 App.js 代码:

import React,  useState, useEffect  from 'react';
import './App.css';
import 'tachyons';

const App = () => 

  const API_KEY = `...`;

  const [searchField, setSearchField] = useState('');
  const [countryField, setCountryField] = useState('');  
  const [currentData, setCurrentData] = useState(null); 
  const [oneCallData, setOneCallData] = useState(null); 

  useEffect(() =>  
    fetch(`https://api.openweathermap.org/data/2.5/weather?q=Cinisi&units=metric&appid=$API_KEY`)
      .then(resp => resp.json())
      .then(dataRecived => 
        setCurrentData(dataRecived);
      )
  , []);

  useEffect(() => 
    fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=38.1562&lon=13.1073&units=metric&exclude=current,minutely,alerts&appid=$API_KEY`)
      .then(resp => resp.json())
      .then(dataRecived => setOneCallData(dataRecived))
  , []);
...


  

提前感谢任何试图给我答案的人

【问题讨论】:

看到这个***.com/questions/55840294/…和namespaceit.com/blog/… 【参考方案1】:

我建议这种类型的重构: 组件应该只有一个 useEffect

fetchData1fetchData2 应该有更有意义的名称。

  const fetchData1 = useCallback(() => 
    fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=38.1562&lon=13.1073&units=metric&exclude=current,minutely,alerts&appid=$API_KEY`)
      .then(resp => resp.json())
      .then(dataRecived => setOneCallData(dataRecived))
  , [API_KEY]);

  const fetchData2 = useCallback(() => 
    fetch(`https://api.openweathermap.org/data/2.5/weather?q=Cinisi&units=metric&appid=$API_KEY`)
      .then(resp => resp.json())
      .then(dataRecived => 
        setCurrentData(dataRecived);
      )
  , [API_KEY]);


  useEffect(() =>  
    fetchData1()
    fetchData2()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  , []);

【讨论】:

现在我有这个警告:Line 42:6: React Hook useEffect has missing dependencies: 'fetchData1' and 'fetchData2'. Either include them or remove the dependency array react-hooks/exhaustive-deps 作为解决方法,按行禁用它: // eslint-disable-next-line react-hooks/exhaustive-deps 解释:***.com/questions/55840294/… 好的,感谢您的回答

以上是关于React Hook useEffect 缺少依赖项:[重复]的主要内容,如果未能解决你的问题,请参考以下文章

React Hook useEffect 缺少依赖项:'props' 由于 useEffect 中有一行

React Hook useEffect 缺少依赖项(没有在 useEffect 中移动函数)

反应 | React Hook useEffect 缺少依赖项

React Hook useEffect 缺少依赖项:'props'

React Hook useEffect 缺少依赖项

React Hook useEffect 缺少依赖项:'list'