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

请求协助解决localhost:3000/hotels路由的Cannot read properties of null (reading 'destination')错误

Problem 1
Problem 2

手动访问localhost:3000/hotels路由时出现Cannot read properties of null (reading 'destination')错误,核心原因是代码中某个变量被当作对象访问destination属性,但该变量实际为null,可按以下步骤解决:

  • 定位错误代码:打开浏览器控制台查看错误栈,找到具体的文件和行号,确认是哪个变量为null。
  • 检查数据来源:这个变量的取值大概率来自路由参数、API请求、本地存储或状态管理工具。手动访问/hotels时,可能缺少了从其他页面跳转时会传递的前置数据,导致变量未被正确赋值。
  • 添加空值防护:在访问.destination属性前先做空值判断,比如使用可选链操作符简化判断:
    // 安全访问属性,若变量为null/undefined则返回undefined
    const destination = targetVariable?.destination;
    
    或者通过条件判断处理空值场景:
    if (targetVariable) {
      // 变量存在时执行逻辑
      const dest = targetVariable.destination;
    } else {
      // 变量为空时的兜底逻辑,比如重定向到目的地选择页
      window.location.href = '/select-destination';
    }
    
  • 路由前置校验:如果/hotels路由依赖前置数据(比如必须先选择目的地),可在路由守卫中添加校验逻辑,若数据不存在则直接重定向到对应页面(比如React Router的Navigate组件、Vue Router的beforeEnter钩子)。
  • 初始化默认值:在数据初始化阶段给变量设置默认空对象,避免出现null:
    // React中初始化状态为默认空对象
    const [hotelRelatedData, setHotelRelatedData] = useState({});
    // API请求时处理返回值,确保不会返回null
    fetch('/api/hotels')
      .then(res => res.json())
      .then(data => setHotelRelatedData(data || {}))
      .catch(() => setHotelRelatedData({}));
    

内容的提问来源于stack exchange,提问作者Md. Tonmoy Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:25:29