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

react-leaflet报错:Cannot read properties of null (reading 'useState') 求助

解决react-leaflet渲染MapContainer时的“Cannot read properties of null (reading 'useState')”错误

问题场景

在React项目里安装react-leaflet实现地图展示,全程按配置步骤操作,但渲染MapContainer组件时抛出错误:Cannot read properties of null (reading 'useState')。

用到的代码如下:

import React, { useState } from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';

import 'leaflet/dist/leaflet.css';
import './Events.css';

function Events() {
  return (
    <MapContainer center={[51.505, -0.09]} zoom={13} scrollWheelZoom={false}>
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Marker position={[51.505, -0.09]}>
        <Popup>
          A pretty CSS3 popup. <br /> Easily customizable.
        </Popup>
      </Marker>
    </MapContainer>
  )
}

export default Events

CSS代码:

#map { height: 180px; }

排查与解决方法

1. 版本不兼容是重灾区

react-leaflet v4及以上版本要求React 18+,如果你的项目用的是React 17或更早版本,必然会出现这个错误。

  • 先检查React版本:终端执行 npm list react 查看具体版本。
  • 要么升级React到最新版:
    npm install react@latest react-dom@latest
    
  • 要么降级react-leaflet到适配React 17的v3.x版本:
    npm install react-leaflet@3.2.5 leaflet@1.9.4
    

2. 容器高度未生效

你的CSS给#map设置了高度,但MapContainer组件未添加id="map"属性,导致容器高度为0,Leaflet初始化失败间接影响React hooks调用。

  • 给MapContainer加上id和内联样式双重保障:
    <MapContainer 
      id="map"
      center={[51.505, -0.09]} 
      zoom={13} 
      scrollWheelZoom={false}
      style={{ height: '180px' }}
    >
    

3. Leaflet全局对象未正确加载

react-leaflet依赖全局的Leaflet对象,部分打包工具可能未正确处理该全局导入。

  • 在项目入口文件(如index.js)中提前导入Leaflet:
    import L from 'leaflet';
    
  • 确保leaflet/dist/leaflet.css的导入位置正确,可在组件或入口文件中导入。

4. React 18严格模式的兼容问题

React 18的严格模式会触发组件两次挂载,旧版本react-leaflet可能对此兼容不佳。

  • 临时移除index.js中的<StrictMode>标签,验证是否解决问题:
    // 修改前
    <React.StrictMode>
      <App />
    </React.StrictMode>
    
    // 修改后
    <App />
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 16:25:24