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

React Native:GooglePlacesAutocomplete onPress报错undefined is not a function

解决React Native中GooglePlacesAutocomplete onPress的undefined is not a function报错

问题诊断

报错undefined is not a function触发位置为HomeScreen.js的GooglePlacesAutocomplete组件onPress回调,结合代码和错误栈,核心原因集中在以下几点:

  1. React导入方式错误
    代码中使用import { React } from 'react';的写法不符合React规范,会导致React对象未正确加载,引发JSX编译或回调执行异常。

  2. Redux Action Creator异常
    如果../slices/navSlice中setOrigin/setDestination未被正确定义为Redux action creator,或者未正确导出,调用dispatch(setOrigin(...))时会因setOrigin是undefined而触发函数调用报错。

  3. 空值访问引发的连锁问题
    虽然设置了details = null的默认值,但当API返回无详细信息的结果时,直接访问details.geometry.location可能触发空值错误,间接导致回调内函数执行异常。

  4. Redux Provider未正确包裹组件
    若HomeScreen未被Redux的Provider组件包裹,useDispatch会返回undefined,调用dispatch时就会报undefined is not a function。

解决方案

1. 修正React导入

将错误的导入语句:

import { React } from 'react';

改为标准默认导入:

import React from 'react';

2. 验证并修复Redux Action Creator

检查../slices/navSlice文件,确保action creator正确定义并导出:

// navSlice.js示例代码
import { createSlice } from '@reduxjs/toolkit';

const navSlice = createSlice({
  name: 'nav',
  initialState: {
    origin: null,
    destination: null,
  },
  reducers: {
    setOrigin: (state, action) => {
      state.origin = action.payload;
    },
    setDestination: (state, action) => {
      state.destination = action.payload;
    },
  },
});

// 必须正确导出action
export const { setOrigin, setDestination } = navSlice.actions;
export default navSlice.reducer;

3. 添加空值判断避免异常

在onPress回调中先校验details是否存在,再执行后续逻辑:

onPress={(data, details = null) => {
  // 无详细信息时直接返回,避免报错
  if (!details?.geometry?.location) return;

  dispatch(setOrigin({
    location: details.geometry.location,
    description: data.description,
  }));

  dispatch(setDestination(null));
}}

4. 确认Redux Provider配置

确保项目根组件已被Provider包裹,例如:

// App.js示例代码
import { Provider } from 'react-redux';
import store from './store';
import HomeScreen from './screens/HomeScreen';

export default function App() {
  return (
    <Provider store={store}>
      <HomeScreen />
    </Provider>
  );
}

验证步骤

  1. 重启React Native开发服务器
  2. 重新构建项目,测试GooglePlacesAutocomplete的选择功能,确认报错消失

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:17:12