useEffect 依赖数组导致无限循环 [英] useEffect dependency array causing infinite loop

查看:29
本文介绍了useEffect 依赖数组导致无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制台中收到以下警告:第 19:6 行:React Hook useEffect 缺少依赖项:'data'.包括它或删除依赖数组 并且 res.data 在我控制台记录它时是一个空数组.

但是当我将 data 传递给依赖项数组时,我确实在控制台中得到了正确的 API 响应,但我得到了一个无限循环.

据我所知,这是使用 useEffect 时最容易陷入的陷阱之一,但我仍然很难思考如何解决这个问题或找到我能真正理解的答案.

对于我的代码当前有什么问题以及如何解决的任何帮助,我们将不胜感激.

import { useState, useEffect } from 'react';从'react-router-dom'导入{链接};从 'axios' 导入 axios;const apiKey = process.env.REACT_APP_NASA_KEY;const NasaPhoto = () =>{const [数据,setData] = useState([]);useEffect(() => {const fetchData = async() =>{const res = 等待 axios(`https://api.nasa.gov/planetary/apod?api_key=${apiKey}`);设置数据(res.data);控制台日志(数据);};fetchData();}, []);返回 (<div><Link to='/'>返回首页</Link><h1>美国宇航局数据</h1>

);};导出默认的 NasaPhoto;

解决方案

在 useEffect 之外编写你的 fetch data 方法并在 useEffect 中调用它,然后将它作为依赖项传递你的代码现在应该是这样的`

const fetchData = async() =>{const res = 等待 axios(https://api.nasa.gov/planetary/apod?api_key=${apiKey});设置数据(res.data);控制台日志(数据);};useEffect(() => {fetchData();}, [fetchData]);

`

I'm getting the following warning in the console: Line 19:6: React Hook useEffect has a missing dependency: 'data'. Either include it or remove the dependency array and res.data is an empty array when I console log it.

But when I pass in data to the dependency array, I do get the correct API response in the console, but I get an infinite loop.

From what I've read, this is one of the most common traps to fall into when using useEffect, but I still have a hard time wrapping my head around how to resolve this or finding an answer I can truly understand.

Any help would be appreciated in what is currently wrong with my code, and how to resolve.

import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

const apiKey = process.env.REACT_APP_NASA_KEY;

const NasaPhoto = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const res = await axios(
        `https://api.nasa.gov/planetary/apod?api_key=${apiKey}`
      );
      setData(res.data);
      console.log(data);
    };
    fetchData();
  }, []);

  return (
    <div>
      <Link to='/'>Return Home</Link>
      <h1>Nasa Data</h1>
    </div>
  );
};
export default NasaPhoto;

解决方案

write your fetch data method outside the useEffect and call it in the useEffect then pass it as a dependency your code should now be something like this `

const fetchData = async () => {
      const res = await axios(
        https://api.nasa.gov/planetary/apod?api_key=${apiKey}
      );
      setData(res.data);
      console.log(data);
    };

useEffect(() => {
   
    fetchData();
  }, [fetchData]);

`

这篇关于useEffect 依赖数组导致无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆