You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React集成Mapbox GL JS出现空白页问题求助

React + Mapbox GL JS 地图组件空白问题

我按照Mapbox官方示例配置了React地图组件,但挂载后页面显示空白,查阅相关问题仍未解决。

问题截图

我的代码如下:

import mapboxgl from '!mapbox-gl'; // eslint-disable-line import/no-webpack-loader-syntax
import { Box } from '@mui/system';

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

import { useDispatch, useSelector } from 'react-redux';
import '../components/propertyMap.css';

const PropertyMap = () => {
  const mapContainer = useRef(null);
  const map = useRef(null);
  const dispatch = useDispatch();
     
  const [property_id, setProperty_id] = useState('');

  const onChange = (e) => {
    setProperty_id(e.target.value);
  };

  mapboxgl.accessToken = process.env.REACT_APP_MAPBOX_TOKEN;
  useEffect(() => {
    if (!mapboxgl.supported()) {
      alert('Your browser does not support Mapbox GL');
    }
    if (map.current) return;
    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: 'mapbox styles here',
      center: [6.459964, 7.548949],
      zoom: 14,
      attributionControl: true,
      interactive: true,
      customAttribution: '&copy',
      boxZoom: true,
    });

    map.current.setCenter([6.459964, 7.548949]);

    // mapboxgl.boxZoomCursor = 'grab';
    map.current.boxZoom.enable();
    map.current.addControl(
      new mapboxgl.NavigationControl(),
      'top-right'
    );
    map.current.addControl(
      new mapboxgl.AttributionControl({ compact: true })
    );
    map.current.resize();
    return () => map.current.remove();
  }, [property]);

  return (
      <Box>
        <Box ref={mapContainer} className='mapContainer' />
      </Box>
  );
};

export default PropertyMap;

排查与修复步骤

1. 给地图容器设置明确宽高

地图容器没有尺寸会直接导致空白,检查propertyMap.css中.mapContainer的样式,必须指定宽高:

.mapContainer {
  width: 100%;
  height: 500px; /* 或使用vh单位,比如height: 80vh */
}

2. 替换无效的Mapbox样式URL

代码中style: 'mapbox styles here'是占位符,必须替换为Mapbox官方提供的有效样式地址,比如:

style: 'mapbox://styles/mapbox/streets-v12',

3. 修复useEffect依赖错误

useEffect依赖数组中的property未定义,会引发渲染异常。如果不需要监听外部变量,改为空数组;如果需要响应property_id变化,替换为property_id:

}, []); // 或 [property_id]

4. 验证Mapbox Token有效性

确保环境变量REACT_APP_MAPBOX_TOKEN已正确配置,可在useEffect中打印验证:

console.log('Mapbox Token:', mapboxgl.accessToken);

如果输出undefined,检查变量名是否以REACT_APP_开头,且已重启开发服务器加载新的环境变量。

5. 调整Token初始化位置

将mapboxgl.accessToken的赋值移到useEffect内部,避免初始化顺序问题:

useEffect(() => {
  mapboxgl.accessToken = process.env.REACT_APP_MAPBOX_TOKEN;
  // 后续地图初始化代码
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:18:18