简体   繁体   English

修复 React Hook useEffect 缺少依赖项

[英]Fix React Hook useEffect has a missing dependency

I am designing a component using the useEffect Hook and I seem to be encountering an error in the code where I have a axios call.我正在使用 useEffect Hook 设计一个组件,我似乎在我有 axios 调用的代码中遇到错误。 I get the error of:我得到以下错误:

Error:错误:

React Hook useEffect has a missing dependency: 'formData'. Either include it or remove the dependency array. You can also do a functional update 'setFormData(f =>...)' if you only need 'formData' in the 'setFormData'

I am not sure why I get this error because I mention in the code where its originating from and since I also use the information outside the hook it seems to be logically correct.我不确定为什么会收到此错误,因为我在代码中提到了它的来源,并且因为我还使用了钩子之外的信息,所以它似乎在逻辑上是正确的。 The end result I am looking for was to have the formData state updated to the values received from the axios request.我正在寻找的最终结果是将 formData state 更新为从 axios 请求收到的值。 However, the values stay the same.但是,这些值保持不变。 So again not sure what I did wrong.所以再次不确定我做错了什么。

Code:代码:

import React, { useState, useEffect } from 'react';
import Aux from '../../hoc/Aux';
import Navbar from './Navbar';
import WeekSelection from './WeekSelection';
import axios from 'axios';



const Landing = () => {

    //useState to set up information
    const[formData,setFormData] = useState({
        name: 'Test',
        artist: 'Test',
        album: 'Test',
        duration: 'Test',
        url: 'https://i.scdn.co/image/ab67706c0000da848d0ce13d55f634e290f744ba'
    });



    const {
        name,
        artist,
        album,
        duration,
        url

    } = formData;

    


           


        useEffect(() => {
              
            axios.post('/')
            .then(res => {
                setFormData({
                    ...formData,
                    name: res.name,
                    artist: res.artist,
                    album: res.album,
                    duation: res.duration,
                    url: res.url
                });

                console.log(name);
                console.log(artist);
                console.log(album);
                console.log(duration);
                console.log(url);
            })
            .catch(err => {
                console.error(err.message);
            });

          

        
        }, []);




    return (
         
        <Aux>
            <div className="myLeft">

                <div className="company-name">
                    <span className="headphones">
                        <i className="fas fa-headphones"></i>
                    </span>
                    <h1 className="titleStyle">SilverStone</h1>
                </div>

                <WeekSelection />
                <WeekSelection />
                <WeekSelection />
                <WeekSelection />
                <WeekSelection />
            </div>

            <div className="myRight">
                <Navbar />
                 
            <div className="test">
                <img src="https://i.scdn.co/image/ab67616d0000b2730a2d690b414896b2bd008a53" alt="Spotify Cover Art" />
            </div>

            <div className="song-data">
                <h2 className="week">Monday</h2>



                <div className="song-box-data">
                    <div className="rectangle-1"></div>
                    <p className="song-styles">Song</p>
                    <div className="music-icon"></div>
                    
                </div>
                <p className="seeYouAgain">See You Again</p>
                    <div className="artist-line">                
                        <div className="by">By:</div>
                        <div className="artist-line-name">Wiz Knalifa ft. Charlie Puth</div>
                    </div>
                    <div className="time-info">                
                        <div className="duration">Duration</div>
                        <div className="minutes">4:54 min</div>
                        <div className="clock">
                            <i className="far fa-clock"></i>
                        </div>
                    </div>
            </div>
            </div>

        </Aux>

     
    )
};


export default Landing;

Since useEffect is simply a function, it can't know by itself what variables are in your component or when they are updated.由于useEffect只是一个 function,它本身无法知道您的组件中有哪些变量或它们何时更新。 As the error message states already, you must include formData in the dependecy array of useEffect (the second parameter of the function), so that the function you provide to useEffect runs each time its dependencies ( formData in this case) update.正如错误消息所述,您必须在useEffect (函数的第二个参数)的依赖数组中包含formData ,以便您提供给useEffect的 function 每次其依赖项(在本例中为formData )更新时运行。

The error message also mentions that you can simply remove the dependency array, which will make your hook run on every update of your component.错误消息还提到您可以简单地删除依赖数组,这将使您的钩子在每次更新组件时运行。 Passing in an empty array to useEffect effectively means "Run this once when the component is created", which contradicts the use of your formData in your hook, since that variable will change throughout the lifetime of the component.将一个空数组传递给useEffect有效地意味着“在创建组件时运行一次”,这与您在钩子中使用formData相矛盾,因为该变量将在组件的整个生命周期内发生变化。 Here is the relevant part of the React documentation: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects这是 React 文档的相关部分: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

If you have any other doubts about React Hooks, I recommend reading the docs carefully.如果您对 React Hooks 有任何其他疑问,我建议您仔细阅读文档。 They are pretty complete and should answer most questions you have about hooks and reactivty.它们非常完整,应该可以回答您关于钩子和反应性的大多数问题。

This is how you can fix it.这就是你可以解决它的方法。

import React, { useState, useEffect } from "react";
import axios from "axios";

const Landing = () => {
  const [formData, setFormData] = useState(null);

  useEffect(() => {
    axios
      .post("/")
      .then(res => {
        const { name, artist, album, duration, url } = res;
        setFormData({ name, artist, album, duration, url });
      })
      .catch(err => {
        console.error(err.message);
      });
  }, []);

  if (!formData) return <p>loading</p>;
  return <div>{JSON.stringify(formData)}</div>;
};

export default Landing;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM