将 useMemo 或 useCallbacks 添加到地图组件会破坏代码并出现错误 "Rendered more hooks than during the previous render "

adding useMemo or useCallbacks to the map component breaks the code with error "Rendered more hooks than during the previous render "

我想做什么

问题描述

   Unhandled Runtime Error
        Error: Rendered more hooks than during the previous render line 27
    import React, { useState, useEffect, useCallback } from 'react';
    import { GoogleMap, useLoadScript } from '@react-google-maps/api';
    
    const libraries = ['places'];
    const mapContainerStyle = {
      width: '100%',
      height: '40vh',
    };
    const center = {
      lat: 25.33800452203996,
      lng: 55.393221974372864,
    };
    const options = {
      zoomControl: true,
    };
    
    const initialMarker = { lat: null, long: null };
    export default function index() {
      const { isLoaded, loadError } = useLoadScript({
        googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
        libraries,
      });
      const [marker, setMarker] = useState(initialMarker);
      if (loadError) return 'Error Loading Maps';
      if (!isLoaded) return 'Loading Maps';
    
      const onMapClick = useCallback((event) => {
        setMarker({
          lat: event.latLng.lat(),
          lng: event.latLng.lng(),
        });
      }, []);
    
      useEffect(() => {
        if (
          google.maps.geometry.spherical.computeDistanceBetween(
            new google.maps.LatLng(center.lat, center.lng),
            new google.maps.LatLng(marker.lat, marker.lng)
          ) > 1000
        ) {
          console.log('out of bounds');
        }
      }, [marker.lat]);
      return (
        <div>
          <GoogleMap
            mapContainerStyle={mapContainerStyle}
            zoom={14}
            options={options}
            center={center}
            onClick={onMapClick}></GoogleMap>
        </div>
      );
    }

参考类似的重新渲染问题

你的问题是这样的:

  if (loadError) return 'Error Loading Maps';
  if (!isLoaded) return 'Loading Maps';

  const onMapClick = useCallback((event) => {
    setMarker({
      lat: event.latLng.lat(),
      lng: event.latLng.lng(),
    });
  }, []);

上述 if 条件可能会取消调用某些挂钩,因此出现警告。你不应该使用钩子 conditionally。您需要重构您的代码。