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

React Native中Pressable onPress报错:Cannot read property 'input' of undefined

问题排查与解决:Cannot read property 'input' of undefined(触发于Pressable的onPress事件)

错误原因

这个错误的核心是**route.params为undefined**,导致访问.input属性时抛出异常。虽然你在route后使用了可选链?.,但params没有加可选链保护——如果route存在但route.params不存在,route?.params.input就会触发"Cannot read property 'input' of undefined"的错误。

另外你的searchPlaces函数存在逻辑错误:当前if (route.params || !selectedDates)的判断逻辑和预期的"校验必填项"完全相反,会导致不该提示的时候弹出警告。

修复方案

1. 给参数访问加上完整的可选链保护

修改Pressable的onPress回调,给params也加上可选链,确保每一层访问都安全:

<Pressable onPress={() => searchPlaces(route?.params?.input)}></Pressable>

这样即使route或route.params是undefined,也只会传递undefined给searchPlaces,不会抛出错误。

2. 修正searchPlaces的校验逻辑

把判断条件改为校验传入的place参数(即input值)和selectedDates是否存在,符合"请填写详情"的业务逻辑:

const searchPlaces = (place) => {
    if (!place || !selectedDates) {
      Alert.alert("Invalid Details", "Please Fill the details", [
        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        { text: 'OK', onPress: () => console.log('OK Pressed') },
      ]);
    }
};

这里直接使用传入的place参数,避免重复依赖route.params,让函数逻辑更独立清晰。

3. 可选:提前校验参数完整性

如果组件依赖route.params.input作为必填项,可以在组件初始化时提前校验并处理:

import { useEffect } from 'react';

// 组件内部
useEffect(() => {
  if (!route?.params?.input) {
    console.warn("搜索关键词参数缺失");
    // 也可以在这里直接弹出提示或跳转到上一页
  }
}, [route]);

内容的提问来源于stack exchange,提问作者Dumindu Karunarathne

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:03:21