传单和反应(未找到地图容器)渲染

时间:2021-01-17 12:49:07

标签: javascript reactjs leaflet

我有一个 React 和 Leaflet.js 组件...

export const MapSetLocationComponent = (props) => {
  React.useEffect(() => {
    let marker = null
    let map = null
    var container = L.DomUtil.get('setLocationMap')
    if (container != null) {
      container._leaflet_id = null
    }

    map = L.map('setLocationMap', {
      center: [51.4556852, -0.9904706],
      zoom: 16,
      layers: [L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {})]
    })

    map.on('click', function (e) {
      if (marker) map.removeLayer(marker)
      marker = L.marker([e.latlng.lat, e.latlng.lng], { title: 'My marker' }).addTo(map)
    })
  })

  return (
    <>
      <h3>Place your pin</h3>
      <div
        id="setLocationMap"
        style={{
          width: '100%',
          height: '300px'
        }}
      />
    </>
  )
}

有时当我加载父组件时会出现以下错误

'未找到地图容器。'

这表明该 div 不可用,因为如果我注释掉那个 div,我会得到同样的错误。

有人有什么想法吗?我需要使用不同的钩子吗?

1 个答案:

答案 0 :(得分:0)

确实,您应该使用 useRef hook 访问实际的 DOM 元素(一旦可用)并将其传递给 Leaflet L.map 工厂。

function myComponent(props) {
  const mapRef = useRef(null);

  useEffect(() => {
    if (mapRef && mapRef.current) {
      L.map(mapRef.current); // ref.current is the actual DOM element
    }
  }, [mapRef]); // re-evaluate once the ref is available

  render (<div ref={mapRef} />)
}

这就是@pilchard 提到的 React Leaflet 的工作原理(简化)。

正如@MattMorgan 所指出的,您渲染的模板最初可能没有插入到实际的 DOM 树中,因此您的 DOM 查询可能会失败。作为一般规则,不要直接摆弄 React 应该管理的 DOM。