【问题标题】:React Google maps API initMap not a function, no packagesReact Google maps API initMap 不是函数,没有包
【发布时间】:2019-02-09 23:31:22
【问题描述】:

收到以下错误,即 initMap 不是函数。我试图不使用任何额外的包来异步加载此脚本或用于 Google Maps API。 我试图只是控制台日志 initMap 以查看脚本何时加载,但我仍然收到它不是函数的错误。我可以将这个函数移到componentDidMount之外,甚至移到App组件之外,但是错误是一样的。

我的猜测是它与脚本通过 document.createElement 加载的事实有关,但 initMap 函数不是,因为当我查看 Google Maps API 的其他示例时,它同时显示了 API URL 和index.html 页面上的 initMap 函数。

这个假设正确吗?有没有办法在不使用任何其他包的情况下轻松地将函数作为脚本或 Google Maps API 在 React 中异步加载?

Uncaught Ib {message: "initMap is not a function", name: "InvalidValueError", stack: "Error↵    at new Ib (https://maps.googleapis.com/m…ZVRgF122wCkVf4P67Y&v=3.32&callback=initMap:163:56"}

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render( < App / > , document.getElementById('root'));
registerServiceWorker();

import React, {
  Component
} from 'react'
import './App.css'
let map;

export default class App extends Component {
  componentDidMount() {

    function initMap() {
      console.log('loaded')
    }

    const script = document.createElement('script')
    script.async = true
    script.defer = true
    script.src = "https://maps.googleapis.com/maps/api/js?key={myAPIkey}=3.32&callback=initMap"
    document.head.appendChild(script)
  }

  render() {
    return ( <
      div > {
        this.map
      } <
      div style = {
        {
          width: 500,
          height: 500
        }
      }
      id = "map" / >
      <
      /div>
    )
  }
}
body {
  font-family: Arial, sans-serif;
  height: 100%;
  margin: 0;
  padding: 0;
}

#map {
  width: 500;
  height: 500;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="theme-color" content="#000000">
  <title>React Map</title>
</head>

<body>
  <div id="root">
  </div>
</body>

</html>

【问题讨论】:

  • callback=initMapwindow 上寻找函数initMap。您的App 组件中的initMap 未附加到window,因此脚本回调不会看到/访问。

标签: javascript reactjs google-maps


【解决方案1】:

事实上,正如 Alexander Staroselsky 所注意到的,callback=initMap 正在窗口中寻找函数 initMap。您应该将 initMap 函数设为全局函数,或者将类中的 initMap 函数分配给 window 对象上的变量,如下所示:

window.initMap = this.initMap.bind(this);

【讨论】:

猜你喜欢
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 2017-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多