【问题标题】:React Hook useEffect has a missing dependency: [duplicate]React Hook useEffect 缺少依赖项:[重复]
【发布时间】: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))
  }, []);
...


  

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

【问题讨论】:

标签: html css reactjs api react-hooks


【解决方案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
  • 好的,感谢您的回答
猜你喜欢
  • 2021-02-23
  • 2019-10-24
  • 2020-10-26
  • 2020-03-07
  • 2020-02-25
  • 2020-06-11
  • 2020-03-30
  • 2020-12-29
  • 2019-09-20
相关资源
最近更新 更多