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

导入@react-google-maps库时触发Super expression错误,寻求解决方案

解决@react-google-maps导入时的"Super expression must either be null or a function, not undefined"错误

嘿,我之前也踩过这个坑!这个错误大多和React组件写法的兼容性、库版本不匹配有关,咱们一步步来搞定它:

常见原因及对应解决方案

1. React.createClass已被废弃,和新版地图库不兼容

@react-google-maps的新版本(尤其是官方现在维护的@react-google-maps/api分支)已经不再支持React.createClass这种旧写法——React早在v16就废弃了这个API,转而推荐ES6 Class组件或者函数组件,强行混用就会触发这个错误。

修改方案:把组件改成ES6 Class写法
替换你原来的React.createClass代码:

const { withScriptjs, withGoogleMap, GoogleMap, Marker } = require('react-google-maps');

class VenueMap extends React.Component {
  constructor(props) {
    super(props);
    const { eventData } = this.props;
    this.state = {
      position: {
        lat: eventData.venue.latitude,
        lng: eventData.venue.longitude,
      },
      defaultZoom: 17
    };
  }

  render() {
    const { position, defaultZoom } = this.state;
    return (
      <GoogleMap
        defaultZoom={defaultZoom}
        defaultCenter={position}
      >
        <Marker position={position} />
      </GoogleMap>
    );
  }
}

// 别忘了用高阶组件包装
const WrappedVenueMap = withScriptjs(withGoogleMap(VenueMap));

2. 使用了过时的地图包版本

如果你还在使用旧的@react-google-maps包(而非官方现在维护的@react-google-maps/api),它很可能和你当前的React版本不兼容。

解决步骤:

  • 先卸载旧包:npm uninstall @react-google-maps
  • 安装官方维护的新版本:npm install @react-google-maps/api
  • 修改导入语句(新版API用法略有调整):
    const { LoadScript, GoogleMap, Marker } = require('@react-google-maps/api');
    
    新版里withScriptjs被替换成了LoadScript组件,用法更直观。

3. 检查React版本兼容性

确保你的React版本满足地图库的要求:

  • 若使用@react-google-maps/api,需要React v16.8+(支持Hooks)
  • 若坚持用旧版@react-google-maps,建议搭配React v15.x,或者把地图库降级到v9.x版本

额外优化建议

如果想让代码更简洁,还可以尝试函数组件+Hooks的写法:

const { LoadScript, GoogleMap, Marker } = require('@react-google-maps/api');

const VenueMap = ({ eventData }) => {
  const position = {
    lat: eventData.venue.latitude,
    lng: eventData.venue.longitude,
  };
  const defaultZoom = 17;

  return (
    <LoadScript googleMapsApiKey="你的谷歌地图API密钥">
      <GoogleMap
        zoom={defaultZoom}
        center={position}
        mapContainerStyle={{ width: '100%', height: '400px' }}
      >
        <Marker position={position} />
      </GoogleMap>
    </LoadScript>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:16:23