在地图组件中添加useMemo或useCallbacks会导致代码中断,并显示错误“渲染的钩子比上一次渲染的钩子更多” 我想做什么问题描述参考来自类似的重新渲染问题

问题描述

我想做什么

  • 在地图上放置标记,并计算标记与地图上静态位置之间的距离。

问题描述

  • 以前,我的useEffect导致重新渲染,现在当我尝试缓存功能时,出现此错误。
   Unhandled Runtime Error
        Error: Rendered more hooks than during the previous render line 27
  • 第27行是我使用useCallback的地方。

  • 在地图上放置标记会导致效果运行并计算距离。

  • 提供给GoogleMap组件的所有选项都在功能组件之外。

  • 为避免重新创建onMapClick函数,我尝试使用UseCallback导致此错误。 useMemo也有同样的错误。

  • 即使我注释掉onMapClick函数并将其从GoogleMap属性中删除,重新呈现问题仍然存在。

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

参考来自类似的重新渲染问题

  • 我也尝试过solution,没有帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)