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

React接入google-maps-react出现Cannot read properties of undefined (reading 'props')报错

问题排查与解决方案

报错根因

你定义的Googlemap是函数式组件,函数组件内部不存在类组件特有的this指向,你直接使用this.props、this.state、this.onMarkerClick等类组件专属语法时,this为undefined,就会触发本次报错。你参考的官方文档示例默认是类组件写法,直接套用到函数组件就会出现该问题。

可选解决方案

方案1:改写为类组件(和官方文档示例对齐)

import React from "react";
import { Map, InfoWindow, Marker, GoogleApiWrapper } from 'google-maps-react';

class Googlemap extends React.Component {
  // 初始化状态
  state = {
    selectedPlace: {}
  }

  // 标记点击回调
  onMarkerClick = (props) => {
    this.setState({
      selectedPlace: props
    })
  }

  // 信息窗关闭回调
  onInfoWindowClose = () => {
    this.setState({
      selectedPlace: {}
    })
  }

  render() {
    return (
      <Map google={this.props.google} zoom={14}>
        <Marker 
          onClick={this.onMarkerClick}
          name={'Current location'} 
        />
        <InfoWindow onClose={this.onInfoWindowClose}>
          <div>
            <h1>{this.state.selectedPlace.name || ''}</h1>
          </div>
        </InfoWindow>
      </Map>
    );
  }
}
export default GoogleApiWrapper({
  apiKey: "MY KEY"
})(Googlemap)

方案2:保留函数组件写法,替换为函数组件专属语法

import React, { useState } from "react";
import { Map, InfoWindow, Marker, GoogleApiWrapper } from 'google-maps-react';

// 函数组件直接通过参数接收props
const Googlemap = (props) => {
  // 用useState Hook管理状态,替代this.state
  const [selectedPlace, setSelectedPlace] = useState({});

  // 直接定义回调函数,不需要绑定this
  const onMarkerClick = (markerProps) => {
    setSelectedPlace(markerProps);
  }

  const onInfoWindowClose = () => {
    setSelectedPlace({});
  }

  return (
    <Map google={props.google} zoom={14}>
      <Marker 
        onClick={onMarkerClick}
        name={'Current location'} 
      />
      <InfoWindow onClose={onInfoWindowClose}>
        <div>
          <h1>{selectedPlace.name || ''}</h1>
        </div>
      </InfoWindow>
    </Map>
  );
}
export default GoogleApiWrapper({
  apiKey: "MY KEY"
})(Googlemap)

注意事项

  • 两个方案都补充了基础的状态初始化和回调实现,你可以根据自身业务需求调整回调内的处理逻辑
  • 代码中添加了|| ''的默认值兜底,避免selectedPlace为空时读取name属性触发新的报错

内容的提问来源于stack exchange,提问作者D.B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:06:03