部署环境下react-google-autocomplete结合AntDesign Input失效求助
解决react-google-autocomplete搭配AntDesign Input部署后失效的问题
问题分析
本地运行正常但部署后失效,已排除GCP配置、CORS、SSL、域名白名单、环境变量等问题,核心大概率是AntD Input与Google Places Widget的ref绑定逻辑在部署环境中存在时机问题,或是Google Places API脚本加载异常。
解决方案
1. 修复Ref绑定逻辑
你当前手动在useEffect中修改placesRef.current的方式不可靠,部署后组件渲染时机与本地存在差异,容易导致绑定失败。改用useLayoutEffect确保DOM更新后立即完成绑定,同时调整ref的获取逻辑:
import React, { useState, useRef, useLayoutEffect } from "react"; import { Input } from "antd"; import { usePlacesWidget } from "react-google-autocomplete"; interface PlaceComponentProps { workLocation?: string; setWorkLocation?: (newValue: string) => void; } function PlaceComponent({ workLocation = '', setWorkLocation, }: PlaceComponentProps) { const [inputValue, setInputValue] = useState(workLocation); const antInputRef = useRef<any>(null); const { ref: placesRef } = usePlacesWidget({ apiKey: process.env.NEXT_PUBLIC_PLACES_API_KEY!, onPlaceSelected: (place) => { const address = place?.formatted_address || ""; setInputValue(address); setWorkLocation?.(address); }, // 可选:配置建议类型,缩小搜索范围 options: { types: ["geocode"], }, }); // 使用useLayoutEffect确保DOM渲染完成后立即绑定原生input useLayoutEffect(() => { if (antInputRef.current) { placesRef.current = antInputRef.current.input; } }, [placesRef, antInputRef]); return ( <Input ref={antInputRef} value={inputValue} onChange={(e) => setInputValue(e.target.value)} size="large" placeholder="请输入工作地点" // 补充占位符属性,解决无占位符问题 /> ); } export default PlaceComponent;
2. 手动注入Google Places API脚本
部署后打开浏览器控制台(F12),检查Network标签是否成功加载https://maps.googleapis.com/maps/api/js开头的脚本。如果未加载,说明组件自动注入脚本的逻辑在部署环境中异常,可手动在_app.tsx中引入:
// _app.tsx import type { AppProps } from 'next/app'; import { useEffect } from 'react'; function MyApp({ Component, pageProps }: AppProps) { useEffect(() => { const script = document.createElement('script'); script.src = `https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_PLACES_API_KEY}&libraries=places`; script.async = true; document.body.appendChild(script); return () => document.body.removeChild(script); }, []); return <Component {...pageProps} />; } export default MyApp;
3. 确认环境变量与API配额
- 部署后在浏览器控制台执行
console.log(process.env.NEXT_PUBLIC_PLACES_API_KEY),确认密钥已正确注入。如果为空,检查部署平台(如Vercel、Netlify)的环境变量配置,确保NEXT_PUBLIC_前缀的变量已被正确暴露。 - 登录Google Cloud Console,进入Places API页面检查配额使用情况和计费状态。免费额度有限,部署后访问量上升可能触发配额限制,需确保有可用配额且已启用计费。
额外提示
- 生产环境不要移除API密钥的域名限制,部署完成后重新配置白名单,仅允许你的生产域名调用API。
- 如果使用Next.js的SSG/SSR模式,需确保Google Places脚本仅在客户端加载,避免服务端渲染时出现错误。
内容的提问来源于stack exchange,提问作者Ahmad Saad
相关产品推荐
相关产品推荐

