如何为Google Places Autocomplete API添加500ms输入触发调用延迟?
实现Google Places Autocomplete输入防抖(延迟500ms调用API)
要实现输入框字符变化后延迟500毫秒调用API,你需要添加**防抖(Debounce)**逻辑来控制API调用时机,以下是修改后的完整代码:
import React, { useRef, useCallback, useEffect } from "react"; import { StandaloneSearchBox, LoadScript } from "@react-google-maps/api"; const PlaceComponent = () => { const inputRef = useRef(null); const debounceTimerRef = useRef(null); // 防抖函数:延迟500ms执行搜索 const debouncedSearch = useCallback((inputValue) => { // 清除之前的定时器,避免重复触发 if (debounceTimerRef.current) { clearTimeout(debounceTimerRef.current); } // 设置新定时器,输入停止500ms后触发API请求 debounceTimerRef.current = setTimeout(() => { if (inputRef.current && inputValue.trim()) { inputRef.current.getPlaces(); } }, 500); }, []); // 监听输入变化,触发防抖逻辑 const handleInputChange = (e) => { debouncedSearch(e.target.value); }; // 处理获取到的地点数据 const handlePlaceChanged = () => { if (!inputRef.current) return; const places = inputRef.current.getPlaces(); // 这里可以根据需求提取地址、坐标等信息 console.log("获取到的地点数据:", places); }; // 组件卸载时清理定时器,避免内存泄漏 useEffect(() => { return () => { if (debounceTimerRef.current) { clearTimeout(debounceTimerRef.current); } }; }, []); return ( <LoadScript googleMapsApiKey="API_KEY" libraries={["places"]} > <StandaloneSearchBox onLoad={(ref) => (inputRef.current = ref)} onPlacesChanged={handlePlaceChanged} > <input id="location" name="location" type="text" className="form-control" placeholder="Enter Location" onChange={handleInputChange} /> </StandaloneSearchBox> </LoadScript> ); }; export default PlaceComponent;
核心逻辑说明:
- 防抖定时器管理:用
debounceTimerRef存储定时器ID,每次输入变化时清除旧定时器,确保只有用户停止输入500ms后才会触发API请求。 - 手动触发搜索:通过
inputRef.current.getPlaces()手动调用Google Places API,替代组件默认的实时触发逻辑。 - 内存泄漏防护:通过
useEffect在组件卸载时清理定时器,避免无用的定时器残留。
内容的提问来源于stack exchange,提问作者Aditya Sheth
相关产品推荐
相关产品推荐

