問題

我正在使用’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庫必須載入”錯誤,我查看了文件,它沒有指定標籤需要放置的位置,只是它需要在某處.

  最佳答案

我在我的一個專案中這樣使用過

 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
}