【问题标题】:React useEffect infinite loop fetch data axiosReact useEffect 无限循环获取数据 axios
【发布时间】:2020-04-21 06:57:53
【问题描述】:

这段代码我得到了一个无限循环。

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

locationAddress 是一个地址数组,我正在尝试使用 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]);

【问题讨论】:

标签: reactjs axios fetch infinite-loop use-effect


【解决方案1】:

这背后的原因是你的依赖数组。基本上,当axios 调用完成时,您将使用setCoordinates 和setLocationAddress 更新您的依赖关系,这会再次触发useEffect 钩子的回调。

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

应该可行的解决方案:

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

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

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

由于缺少coordinates 和locationAddress,您可能会收到一条警告消息,您可以在依赖数组前的一行使用// eslint-disable-next-line react-hooks/exhaustive-deps 注释来禁用它们。

希望对你有帮助!

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 2020-04-14
      • 2020-08-19
      • 2022-11-20
      • 2020-09-06
      • 2021-01-21
      相关资源
      最近更新 更多