如何将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
- No
thisin Function Components: You tried referencingthis.initMap, but function components don't have athiscontext. Instead, we defineinitMapdirectly inside the useEffect hook where it can accesssetGmapsLoaded. - 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, matchingcomponentDidMountbehavior. - Cleanup Logic: Added a cleanup function to remove the script tag and delete the
window.initMapproperty when the component unmounts. This prevents memory leaks and avoids conflicts if the component re-mounts later. - CamelCase Consistency: Renamed
setgmapsLoadedtosetGmapsLoadedto follow standard React state setter naming conventions.
内容的提问来源于stack exchange,提问作者benpalmer
相关产品推荐
相关产品推荐

