React useEffect infinite loop fetch data axios

前端 未结 2 672
一向
一向 2021-01-15 18:00

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 i

2条回答
  •  天涯浪人
    2021-01-15 18:26

    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!

提交回复
热议问题