【问题标题】:Getting infinite loop when making an axios get request发出 axios get 请求时出现无限循环
【发布时间】:2021-09-02 02:08:24
【问题描述】:

当我使用 Axios 向 api 发出 get 请求时,我在 useEffect 钩子中得到一个无限循环,我确信添加“[]”的第二个选项会告诉它只运行一次。有什么我遗漏或忽略的吗? console.log 显示它正在无限循环。

import React, {useEffect, useState} from 'react';
import axios from 'axios';
import { getCookie } from '../utils/util';




const Details = () => {

    const [data, setData] = useState(null);
    let country;    
    const queryURL = `https://restcountries.eu/rest/v2/name/`;

    useEffect(() => {
        country = getCookie('title');
        console.log(country);
        axios.get(queryURL + country).then((res) => {
            setData(res.data);
        }, []);

    })

    return (
        <>
            details
        </>
    )
}

export default Details;

【问题讨论】:

    标签: javascript reactjs api axios


    【解决方案1】:

    需要在callback函数后面放空数组(依赖):

    改为:

    useEffect(() => {
      country = getCookie("title");
      console.log(country);
      axios.get(queryURL + country).then((res) => {
        setData(res.data);
      });
    }, []);
    

    【讨论】:

    • 如果有帮助,您应该将答案标记为正确。
    • 欣赏! @MrMythical
    猜你喜欢
    • 2020-01-30
    • 1970-01-01
    • 2021-06-07
    • 2021-11-03
    • 2021-07-27
    • 2020-12-31
    • 2019-09-07
    • 2021-05-01
    • 2018-04-11
    相关资源
    最近更新 更多