如何在 React 项目中加载 Google Places JS API 库?

How to load the Google Places JS API Library in a React Project?

我正在使用 'react-places-autocomplete' 库。我知道我必须使用我的密钥加载 API。我无法弄清楚将密钥脚本放在哪里才能使程序运行。

我看到一个 Whosebug 页面,有人说要在 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 library must be loaded" 错误,我查看了文档,它没有指定标签需要放置的位置,只是它需要在某个地方。

我在我的一个项目中就是这样使用的

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
}