使用React状态,如何在添加新标记之前从Google地图中删除标记?

问题描述 投票:0回答:1

我有一个React应用,可显示带有一些标记的地图。通过单击可从Google Maps API获取新位置的按钮来刷新地图标记。我想在每次刷新时从地图上删除以前的位置标记。

import React, { useEffect, useState } from 'react';

function Map(props) {
  const [markers, setMarkers] = useState();

  function clearMarkers() {
    for(let i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
    }
  }

  useEffect(() => {

    clearMarkers();

    if(props.locations.length) {
      const googleMarkers = [];

      for(let i = 0; i < props.locations.length; i++) {
        const marker = new window.google.maps.Marker({...});
        googleMarkers.push(marker);
      }

      setMarkers(googleMarkers);
    }
  }, [props.locations, props.map]);
}

我有工作,但是我从React得到警告。

React Hook useEffect缺少依赖项:'clearMarkers'。包括它或删除依赖项数组

我需要依赖项数组,因此标记仅在有新的props.locations时刷新,但是当我将其包含在依赖项数组中时,会出现无限循环。

我如何在添加新标记之前清除地图上的标记没有React发出警告?还是我不应该担心警告?

javascript reactjs google-maps google-maps-markers react-state
1个回答
0
投票

您可以尝试并记住您的clearMarkers函数,并使用useCallback将其添加到useEffect的依赖项数组中>

随着代码的读取,您正在每个渲染器上创建一个新函数,因此,如果将函数添加到依赖项数组,则每次都会触发该效果

这应该工作

const cb = useCallback(function clearMarkers() {
    for(let i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
    }
  }, [markers.length]);
useEffect(() => {
    cb();
    if (props.locations.length) {
      const googleMarkers = [];
      for (let i = 0; i < props.locations.length; i++) {
        const marker = `marker #${i}`;
        googleMarkers.push(marker);
      }
      setMarkers(googleMarkers);
    }
  }, [props.locations, cb]);

但是您也可以只在useEffect内部添加清除循环,并将markers.length添加到依赖项数组中

© www.soinside.com 2019 - 2024. All rights reserved.