React useEffect infinite loop fetch data axios

陌路散爱 提交于 2021-02-16 09:12:09

问题


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

回答1:


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!




回答2:


You are interating over the locationAddress array, calling the api and changing the same array inside the loop. This is causing the infinite loop. Why do you need to set the location address again? If you receive more information, put it in another array.



来源:https://stackoverflow.com/questions/59566248/react-useeffect-infinite-loop-fetch-data-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!