【问题标题】:How to load the Google Places JS API Library in a React Project?如何在 React 项目中加载 Google Places JS API 库?
【发布时间】:2019-09-29 05:46:44
【问题描述】:

我正在使用“react-places-autocomplete”库。我了解我必须使用我的密钥加载 API。我不知道在哪里放置密钥的脚本,这样程序才能运行。

我看到一个 StackOverflow 页面,有人说要在 index.js 中静态加载它,我试过了:

import 'react-places-autocomplete';
...
ReactDOM.render(
    <div>
    <BrowserRouter>
        <App />
    </BrowserRouter>
    <script src="https://maps.googleapis.com/maps/api/js? 
     key=MY_KEY&libraries=places"></script>
    </div>
    , document.getElementById('root'));

这个不行,我也试过直接在组件中加载(好像不太对):

class My_Component extends React.Component {

...

render() {
    return (
        <div>
            <script src="https://maps.googleapis.com/maps/api/js? 
     key=MY_KEY&libraries=places"></script>
            <PlacesAutocomplete
                value={this.state.address}
                onChange={this.handleChange}
                onSelect={this.handleSelect}
            >

         ....

         </div>
        );
    }
}

使用这些方法,我不断收到“必须加载 Google Maps JavaScript API 库”错误,我查看了文档,它没有指定标签需要放置在哪里,只是它需要放在某个地方.

【问题讨论】:

标签: javascript reactjs google-places-api googleplacesautocomplete


【解决方案1】:

我在我的一个项目中使用过这种方式

class PlacesAutocomplete1 extends React.Component {
  constructor(props) {
  super(props);
  this.state = {
    googleMapsReady: false,
  };
}

componentDidMount() {
    script is loaded here and state is set to true after loading
    this.loadGoogleMaps(() => {
    // Work to do after the library loads.
    this.setState({ googleMapsReady: true });
  });
}

componentWillUnmount() {
  // unload script when needed to avoid multiple google scripts loaded warning
  this.unloadGoogleMaps();
}

loadGoogleMaps = callback => {
    const existingScript = document.getElementById("googlePlacesScript");
    if (!existingScript) {
        const script = document.createElement("script");
        script.src =
            "https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places";
        script.id = "googleMaps";
        document.body.appendChild(script);
        //action to do after a script is loaded in our case setState
        script.onload = () => {
            if (callback) callback();
        };
    }
    if (existingScript && callback) callback();
};

unloadGoogleMaps = () => {
    let googlePlacesScript = document.getElementById("googlePlacesScript");
    if (googlePlacesScript) {
        googlePlacesScript.remove();
    }
};

render() {
    if (!this.state.googleMapsReady) {
        return <p>Loading</p>;
    }
    return (
        // do something you needed when script is loaded
}

【讨论】:

  • 非常感谢,您让我头疼不已。这基本上是您需要使用这个库的任何时候的样板吗?我在文档中没有看到类似的东西。
  • 在 react 中有很多方法可以实现这一点。你可以说这是其中之一。如果它解决了您的问题,请使用勾号接受答案
  • id 好像不对,create 和 getElementById 应该是一样的
猜你喜欢
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
  • 2019-09-18
  • 2018-06-20
  • 1970-01-01
相关资源
最近更新 更多