You need to enable JavaScript to run this app. Gatsby项目中父组件activeItem更新时如何触发Mapbox地图弹窗高亮路由
优惠活动
大模型
产品
解决方案
定价
更多

Gatsby项目中父组件activeItem更新时如何触发Mapbox地图弹窗高亮路由

解决方案

核心思路

核心问题是Mapbox实例被限制在初始化的useEffect作用域内,外部无法访问,正确的做法是用useRef存储Mapbox实例和弹出层实例——useRef的current属性可以跨渲染周期存储可变值,且不会触发组件重渲染,完美适配第三方SDK实例的存储需求。

具体实现步骤

  • 新增两个ref分别存储map实例和popup实例,代替之前在useEffect内部定义的局部变量
  • 新增单独的useEffect监听activeItem变化,当activeItem更新且map实例已加载完成时,触发对应路线的高亮和弹窗逻辑
  • 补全父组件状态同步逻辑,获取到路线数据后调用传入的updateList同步状态

修改后完整代码

import { useRef, useState, useEffect } from 'react'
import mapboxgl from 'mapbox-gl'

const EmbeddedMap = ({ updateList, activeItem }) => {
  const mapContainerRef = useRef(null)
  // 新增ref存储map实例和popup实例
  const mapRef = useRef(null)
  const popupRef = useRef(null)
  const [list, setList] = useState([])

  // 地图初始化逻辑
  useEffect(() => {
    // 避免重复初始化
    if (mapRef.current) return

    const map = new mapboxgl.Map({
      container: mapContainerRef.current,
      accessToken: process.env.GATSBY_MAPBOX_TOKEN,
      style: "mapbox://styles/mapbox/...",
      center: [-90.836, 51.134],
      zoom: 6,
    })
    // 把实例存到ref里
    mapRef.current = map
    const popup = new mapboxgl.Popup()
    popupRef.current = popup

    const getUniqueFeatures = (array, comparatorProperty) =>
      array.filter(
        (v, i, a) =>
          a.findIndex(
            t =>
              t.properties[comparatorProperty] ===
              v.properties[comparatorProperty]
          ) === i
      )

    const updateMap = () => {
      const features = map.queryRenderedFeatures({ layers: ["data"] })
      if (features) {
        const uniqueFeatures = getUniqueFeatures(features, "post_id")
        setList(uniqueFeatures)
        // 同步给父组件更新列表
        updateList(uniqueFeatures)
      }
    }

    map.on("load", () => {
      updateMap()

      map.on("movestart", () => {
        map.setFilter("data", ["has", "title"])
      })

      map.on("moveend", () => {
        updateMap()
      })

      map.on("mousemove", "data", e => {
        map.getCanvas().style.cursor = "pointer"
        const feature = e.features[0]
        setPopup(map, popup, feature)
      })

      map.on("mouseleave", "data", () => {
        map.getCanvas().style.cursor = ""
        popup.remove()
      })

      map.on("click", "data", e => {
        const feature = e.features[0]
        map.flyTo({
          center: feature.geometry.coordinates[0],
        })
        setPopup(map, popup, feature)
      })
    })

    return () => {
      map.remove()
      mapRef.current = null
    }
  }, [updateList])

  // 监听activeItem变化触发弹窗逻辑
  useEffect(() => {
    const map = mapRef.current
    const popup = popupRef.current
    // 地图没加载完成、没有activeItem时直接返回
    if (!map || !popup || !activeItem) return

    // 按唯一标识匹配对应feature,这里用post_id匹配,可替换为实际的唯一字段
    const allFeatures = map.queryRenderedFeatures({ layers: ["data"] })
    const targetFeature = allFeatures.find(f => f.properties.post_id === activeItem.post_id)

    if (targetFeature) {
      // 可选:自动飞到对应路线位置
      map.flyTo({
        center: targetFeature.geometry.coordinates[0],
        duration: 600
      })
      // 弹出对应弹窗
      setPopup(map, popup, targetFeature)
    }
  }, [activeItem])

  return (
    <div>
      <EmbeddedMapStyled ref={mapContainerRef} />
    </div>
  )
}

注意事项

  • 如果你自定义的setPopup方法是在组件其他位置定义的,记得保证它可以正常接收map、popup、feature三个参数,或者直接把逻辑搬到当前作用域内
  • 如果列表hover时activeItem会频繁更新,可以加防抖优化,避免频繁触发flyTo和弹窗重绘
  • 原方案用useState存map实例不生效的原因是useState更新是异步的,setMap执行后不会立刻更新state值,而useRef的current属性是同步更新的,所以更适合存储这类第三方实例

内容的提问来源于stack exchange,提问作者Jonathan Lauwers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 15:15:06