【问题标题】:How to add react-router-link to mapbox marker created with forEach method如何将 react-router-link 添加到使用 forEach 方法创建的 mapbox 标记中
【发布时间】:2021-10-15 09:28:41
【问题描述】:

我对 mapbox 库不太熟悉,我有一个问题:如何将路由器链接添加到每个 mapbox 标记?因为如果我使用 window.location 它可以工作,但是每次我点击标记时我的地图组件都会重新渲染。基本上,我要做的就是将 window.location 更改为 Router-link。

rtdb.ref('/').once('value').then((snapshot) => {
  if (snapshot.exists()) {
    snapshot.val().features.forEach(function (marker) {
      
      new mapboxgl.Marker().setLngLat(marker.geometry.coordinates).addTo(map).getElement().addEventListener('click', () => {
        //<Link to={'/markerinfo/' + marker.properties.docID}/> 
        //window.location=('/markerinfo/'+marker.properties.docID)
      })
    }
    )
  } else console.log("No data available")
}).catch((error) => {
  console.error(error);
});

【问题讨论】:

    标签: reactjs react-router mapbox mapbox-gl-js mapbox-marker


    【解决方案1】:

    我认为您正在寻找“如何以编程方式导航” 尝试使用

    import { useHistory } from "react-router-dom";
    function YourComponent(){
      const history = useHistory();
    
    
    }
    

    然后在你的函数中

    rtdb.ref('/').once('value').then((snapshot) => {
      if (snapshot.exists()) {
        snapshot.val().features.forEach(function (marker) {
          
          new mapboxgl.Marker().setLngLat(marker.geometry.coordinates).addTo(map).getElement().addEventListener('click', () => {
          
             history.push('/markerinfo/'+marker.properties.docID);
          })
        }
        )
      } else console.log("No data available")
    }).catch((error) => {
      console.error(error);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多