Google 从 15.x 升级后在 React 16 中出现错误

Google places error in React 16 after upgrade from 15.x

我刚刚将我的 React 应用程序从 15.x 升级到 React 16.0,现在出现以下错误。除了现在是 React 16.0 应用程序之外,代码本身没有改变。

'google' is not defined no-undef

我在我创建的 util 方法中使用了自动完成功能,如下所示:

const map = new google.maps.Map(document.createElement('div'));
const googlePlacesAutocomplete = new google.maps.places.AutocompleteService();
const googlePlacesService = new google.maps.places.PlacesService(map);

export const googlePlacesAutoComplete = (keyword, callback) => {

    googlePlacesAutocomplete.getQueryPredictions({input: keyword}, (predictions, status) => {

        if(status !== google.maps.places.PlacesServiceStatus.OK) return callback(null);
        return callback(predictions);
    });
}

我只是从静态 HTML 页面指向 Google Places 库作为我的 React 应用程序的入口点。

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=my-api-key"></script>

知道出了什么问题吗?有什么解决这个问题的建议吗?

你试过'window.google'了吗? 'google'是全局的,建议不要按原样使用全局变量。

此外,如果可以,请尝试将“google”添加为模块,以确保它在使用前已加载。 并可能避免使用全局变量或任何可以覆盖其值的东西。