繁体   English   中英

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

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

我正在使用“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 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM