React useEffect 无限循环获取数据 axios [英] React useEffect infinite loop fetch data axios

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

问题描述

这段代码导致我陷入无限循环.

我一直在尝试其他帖子中的一些解决方案,但它们不起作用.

locationAddress 是一个地址数组,我正在尝试使用 Google Maps Geocode API 获取坐标.

 const reducer = (state, action) =>{开关(动作.类型){案例添加":返回 [...状态,{地址:action.address,名称:action.name,id:action.id}];案例删除":返回 state.filter((_, index) => index !== action.index)默认:返回状态;}}const [locationAddress, setLocationAddress] = useReducer(reducer, []);const [坐标,setCoordinates] = useState([]);useEffect(() => {const fetchLocation = async() =>{for(let i = 0; i < locationAddress.length; i++) {const response = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {参数:{地址:locationAddress[i].address,键:'MyAPIKey'}}).then(响应 => {setLocationAddress({locationAddress: response.data});setCoordinates([...坐标, {lat: response.data.results[0].geometry.location.lat, lng: response.data.results[0].geometry.location.lng}]);}).catch(错误=> {控制台日志(错误)});}}fetchLocation();},[坐标,位置地址]);

解决方案

这背后的原因是你的依赖数组.基本上,当 axios 调用完成时,您正在使用 setCoordinatessetLocationAddress 更新您的依赖项,这将再次触发 useEffect 钩子的回调.

如果您将 [coordinates, locationAddress] 替换为 setter 函数 [setCoordinates, setLocationAddress] 那么它将按预期工作.>

应该可行的解决方案:

const [locationAddress, setLocationAddress] = useReducer(reducer, []);const [坐标,setCoordinates] = useState([]);useEffect(() => {//... 删除定义以在答案中更好地表示fetchLocation();}, [setCoordinates, setLocationAddress]);

由于缺少 coordinateslocationAddress,您可能会收到警告消息,您可以使用 //eslint-disable-next-line react-hooks/禁用它们Exclusive-deps 在依赖数组前注释一行.

希望能帮到你!

I'm getting an infinite loop with this code.

I've been trying some of the solutions from another posts but they don't work.

locationAddress is an array of addresses and I'm trying to get the coordinates using the Google Maps Geocode API.

    const reducer = (state, action) => {
        switch (action.type) {
            case 'add':
                return [
                    ...state,
                    {
                        address: action.address,
                        name: action.name,
                        id: action.id
                    }
                ];
            case 'remove':
                return state.filter((_, index) => index !== action.index)
            default:
                return state;
        }
    }

    const [locationAddress, setLocationAddress] = useReducer(reducer, []);

    const [coordinates, setCoordinates] = useState([]);

    useEffect(() => {
        const fetchLocation = async () => {
            for(let i = 0; i < locationAddress.length; i++) {
                const response = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
                    params: {
                        address: locationAddress[i].address,
                        key: 'MyAPIKey'
                    }

                })
                .then(response => {
                        setLocationAddress({locationAddress: response.data});
                        setCoordinates([...coordinates, {lat: response.data.results[0].geometry.location.lat, lng: response.data.results[0].geometry.location.lng}]);
                        }
                    )
                .catch(error => {
                    console.log(error)
                });
            }
        }
        fetchLocation();
    },[coordinates, locationAddress]);

解决方案

The reason behind that is your dependency array. Basically when axios call finished you are updating your dependencies with setCoordinates and setLocationAddress which triggers again the useEffect hook's callback.

If you replace [coordinates, locationAddress] with the setter functions [setCoordinates, setLocationAddress] then it will work as expected.

The solution which should work:

const [locationAddress, setLocationAddress] = useReducer(reducer, []);
const [coordinates, setCoordinates] = useState([]);

useEffect(() => {
    // ... removed definition for better representation in the answer

    fetchLocation();
}, [setCoordinates, setLocationAddress]);

You might have a warning message because of missing coordinates and locationAddress which you can disable with // eslint-disable-next-line react-hooks/exhaustive-deps comment one line before the dependency array.

I hope that helps!

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

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