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

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

问题描述

此代码使我陷入无限循环.

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是一个地址数组,我正在尝试使用Google Maps Geocode API获取坐标.

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]);

推荐答案

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

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.

如果用设置器功能[setCoordinatessetLocationAddress]替换[coordinates, locationAddress],则它将按预期工作.

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]);

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

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.

希望对您有帮助!

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

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