React useEffect 无限循环获取数据 axios

React useEffect infinite loop fetch data axios

我遇到此代码的无限循环。

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

locationAddress 是一个地址数组,我正在尝试使用 Google 地图地理编码 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 挂钩的回调。

如果您将 [coordinates, locationAddress] 替换为 setter 函数 [setCoordinatessetLocationAddress],那么它将按预期工作。

应该有效的解决方案:

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 在依赖项数组前一行注释来禁用它们。

希望对您有所帮助!

您正在对 locationAddress 数组进行交互,调用 api 并在循环内更改同一数组。这导致了无限循环。为什么需要重新设置location地址?如果您收到更多信息,请将其放入另一个数组中。