首页 > 解决方案 > 修复 React Hook useEffect 缺少依赖项

问题描述

我正在使用 useEffect Hook 设计一个组件,我似乎在我有 axios 调用的代码中遇到错误。我得到以下错误:

错误:

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'

我不确定为什么会收到此错误,因为我在代码中提到了它的来源,并且因为我还使用了钩子之外的信息,所以它似乎在逻辑上是正确的。我正在寻找的最终结果是将 formData 状态更新为从 axios 请求接收到的值。但是,这些值保持不变。所以再次不确定我做错了什么。

代码:

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;

标签: javascriptreactjs

解决方案


Since useEffect is simply a function, it can't know by itself what variables are in your component or when they are updated. 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.

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. Here is the relevant part of the React documentation : 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. They are pretty complete and should answer most questions you have about hooks and reactivty.


推荐阅读