【问题标题】:Load Google Maps in React App - 'map is assigned a value but never used'在 React 应用程序中加载谷歌地图 - '地图被分配了一个值,但从未使用过'
【发布时间】:2018-10-21 14:17:31
【问题描述】:

我正在尝试使用 React 在页面上呈现地图,但地图从未显示。在控制台中,我可以看到此警告,并且似乎没有在任何地方调用该变量。我在教程中看到过类似这样的常见实现,但我不明白为什么它没有在这里渲染。

这是我的 App 组件代码:

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

class App extends Component {

  componentDidMount() {
      this.renderMap();
  }

  renderMap = () => {
      this.loadScript("https://maps.googleapis.com/maps/api/" +
        "js?key=AIzaSyC1FpwqY0kv0hxQYPtGnn54ag14jHUI6Ow&callback=initMap");
      window.initMap = this.initMap;
  };

  loadScript = (url) => {
      const index = window.document.getElementsByTagName("script")[0];
      const script = window.document.createElement("script");
      script.src = url;
      script.async = true;
      script.defer = true;
      index.parentNode.insertBefore(script, index);
  };

  initMap = () => {
      var map = new window.google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
      });
  };

  render() {
      return (
          <div className="App">
              <h1>Google Maps in React App</h1>
              <div id="map"> </div>
          </div>
      );
  }
}

export default App;

这是控制台中的警告:

webpackHotDevClient.js:120 ./src/App.js
Line 26:  'map' is assigned a value but never used  no-unused-vars

我已经在组件中动态加载了脚本。有人可以帮我吗?谢谢。

【问题讨论】:

    标签: reactjs google-maps


    【解决方案1】:

    这只是意味着您定义了变量map,但不要使用它。此警告来自 eslint 而不是谷歌地图。在initMap,你可以添加return map

    此外,您还可以在 eslint 配置中禁用此 eslint 规则 as explained here

    【讨论】:

    • 我已返回地图但仍未渲染。另一个问题出现在我创建了一个新的 api 密钥并且我收到了超出配额限制的错误。我该如何解决这些问题?谢谢
    • 您的地图可能永远不会呈现...我认为您将无法使用这些 Api 密钥,因为它们已为该帐户使用了 Google 地图的最大配额。这与您的代码无关,可能需要关于 SO 的另一个问题
    • 好的,谢谢。回到关于这个问题的问题。请告诉我为什么它仍然不渲染,即使键是有序的
    • 您是否在 console.log 中收到消息?你可能会看到this answer I wrote some time ago
    • 我已经通过使用 npm pkg - react-google-maps 解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 2016-04-15
    • 1970-01-01
    • 2015-04-22
    • 2013-07-03
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多