使用react-native-google-places-autocomplete时出现filter未定义错误求助
解决react-native-google-places-autocomplete的"cannot read property 'filter' of undefined"错误
问题分析
错误触发于模块内部的buildRowsFromResults函数,且此时results为空数组,说明模块尝试对某个未定义的属性调用filter方法——大概率是默认期望访问results.predictions数组,但API返回的空结果结构不符合模块预期,导致该属性为undefined。
解决方案
指定API返回字段并补全查询参数
Google Places API的默认返回结构可能缺少模块需要的字段,显式指定fields参数确保返回数据符合预期,同时添加language等参数避免解析异常:<GooglePlacesAutocomplete placeholder="Type a place" query={{ key: 'My-API-Key', fields: 'formatted_address,name,geometry', // 按需指定字段 language: 'zh-CN' // 替换为你的目标语言 }} />自定义结果过滤逻辑,避免undefined调用
用filterResults属性提前处理空结果,确保始终返回有效数组:<GooglePlacesAutocomplete placeholder="Type a place" query={{ key: 'My-API-Key' }} filterResults={(results) => results?.predictions || []} />升级模块到最新版本
旧版本可能存在空结果处理的bug,执行以下命令升级:# npm npm update react-native-google-places-autocomplete # yarn yarn upgrade react-native-google-places-autocomplete添加错误与空结果回调
通过onFail和onNotFound捕获异常,同时开启fetchDetails确保响应被正确解析:<GooglePlacesAutocomplete placeholder="Type a place" query={{ key: 'My-API-Key' }} fetchDetails={true} onFail={(error) => console.error('API请求错误:', error)} onNotFound={() => console.log('未找到匹配地点')} />
内容的提问来源于stack exchange,提问作者Az3ssin
相关产品推荐
相关产品推荐

