最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Hook useEffect has a missing dependency: 'id'. Either include it or remove the dependency arr

programmeradmin4浏览0评论

sorry for the trivial question (maybe) but I've been hitting my head for hours. where is the mistake?

import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { SingleCoin } from '../config/api';

const {id} = useParams();
const [coins, setCoins] = useState();
const {currency, symbol} = CryptoState();
    
useEffect(()=>{
    const fetchCoins = async () => {
        const {data} = await axios.get(SingleCoin(id));
        setCoins(data);
    };
    fetchCoins();
}, []);

React Hook useEffect has a missing dependency: 'id'. Either include it or remove the dependency array

sorry for the trivial question (maybe) but I've been hitting my head for hours. where is the mistake?

import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { SingleCoin } from '../config/api';

const {id} = useParams();
const [coins, setCoins] = useState();
const {currency, symbol} = CryptoState();
    
useEffect(()=>{
    const fetchCoins = async () => {
        const {data} = await axios.get(SingleCoin(id));
        setCoins(data);
    };
    fetchCoins();
}, []);

React Hook useEffect has a missing dependency: 'id'. Either include it or remove the dependency array

Share Improve this question edited Jul 3, 2022 at 18:45 Tommaso Ceredi asked Jul 3, 2022 at 18:42 Tommaso CerediTommaso Ceredi 971 gold badge3 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Any variable that you use in the useEffect function needs to be in the dependency array, so that it is can be monitored and the useEffect will only be run when that variable changes.

useEffect(()=>{
    const fetchCoins = async () => {
        const {data} = await axios.get(SingleCoin(id));
        setCoins(data);
    };
    fetchCoins();
}, [id]);

Add id to the array that is the second parameter of useEffect to clear this error. Reference

useEffect and some other hooks need a dependency array provided. It's the last argument passed as an array. The dependencies tell the hooks which variables or elements to observe for changes. If a dependency changes, the hook should also expect a new behavior and will therefor update.

To fix your issue, you need to provide the id in your dependency array as the warning states like so: React Hook useEffect has a missing dependency: 'id'

useEffect(()=>{
    const fetchCoins = async () => {
        const {data} = await axios.get(SingleCoin(id));
        setCoins(data);
    };
    fetchCoins();
}, [id]);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论