You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Google Maps JavaScript API加载校验的React类组件方案转换为函数组件(Hooks实现)

Fixing the Google Maps Places Autocomplete Hook Conversion

Got it, let's get that Hooks conversion working for you. Your attempt hit a couple of common function component pitfalls—here's the corrected code and a breakdown of what was off:

Corrected Function Component Code

import { useState, useEffect } from 'react';
import PlacesAutocomplete from './your-path-to-places-autocomplete'; // Update this import path

const PlacesAutocompleteWrapper = () => {
  const [gmapsLoaded, setGmapsLoaded] = useState(false);

  useEffect(() => {
    // Define initMap directly in useEffect to avoid scope issues
    const initMap = () => {
      setGmapsLoaded(true);
    };

    // Attach the function to window so Google Maps can trigger it
    window.initMap = initMap;

    // Create and inject the Google Maps script
    const gmapScriptEl = document.createElement('script');
    gmapScriptEl.src = `https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap`;
    document.body.appendChild(gmapScriptEl);

    // Cleanup: Remove script and window property on unmount to prevent leaks
    return () => {
      document.body.removeChild(gmapScriptEl);
      delete window.initMap;
    };
  }, []); // Empty array ensures this runs once (like componentDidMount)

  return (
    <div>
      {gmapsLoaded && <PlacesAutocomplete />}
    </div>
  );
};

export default PlacesAutocompleteWrapper;

Key Fixes from Your Attempt

  1. No this in Function Components: You tried referencing this.initMap, but function components don't have a this context. Instead, we define initMap directly inside the useEffect hook where it can access setGmapsLoaded.
  2. Missing Dependency Array: Your useEffect didn't have a dependency array, which would cause it to run on every re-render—leading to duplicate script tags. The empty [] array ensures it runs exactly once on mount, matching componentDidMount behavior.
  3. Cleanup Logic: Added a cleanup function to remove the script tag and delete the window.initMap property when the component unmounts. This prevents memory leaks and avoids conflicts if the component re-mounts later.
  4. CamelCase Consistency: Renamed setgmapsLoaded to setGmapsLoaded to follow standard React state setter naming conventions.

内容的提问来源于stack exchange,提问作者benpalmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:47:30