You need to enable JavaScript to run this app. React开发中对象解构报错:props.singleInfo为undefined无法解构heading属性
优惠活动
大模型
产品
解决方案
定价
更多

React开发中对象解构报错:props.singleInfo为undefined无法解构heading属性

报错核心原因

出现Cannot destructure property heading of props.singleInfo as it is undefined的根源是组件使用逻辑存在两个逻辑断层:

  • 你将DetailsOfDestination同时作为首页列表渲染组件和路由独立详情页组件使用:列表渲染时循环FakeData传入了singleInfo属性,控制台能正常打印日志;但路由跳转后是直接将该组件挂载到路由出口,没有任何逻辑为它传入singleInfo属性,接收值为undefined,自然触发解构报错。
  • 所有卡片的跳转路径完全一致,都是硬编码的/DetailsOfDestination,没有携带对应目的地的唯一标识,哪怕路由跳转成功,也无法定位需要展示的具体数据条目。
分步修复方案

1. 重构首页卡片的跳转绑定

删除PlaceDetail组件里无效的属性解构(代码中const { heading, img, text } = props.place;从未被传入对应place属性,属于冗余代码),将每个卡片的跳转路径绑定对应目的地的唯一标识:

import React, { useState } from "react";
import { Link } from "react-router-dom";
import DetailsOfDestination from "../DetailsOfDestination/DetailsOfDestination";
import FakeData from "../Fakedata/FakeData";

const PlaceDetail = () => {
  const [info, setInfo] = useState(FakeData);
  return (
    <div>
      {info.map((singleInfo) => (
        <div key={singleInfo.heading} className="destination-card">
          <Link to={`/DetailsOfDestination/${singleInfo.heading}`}>
            <img src={singleInfo.img} alt={singleInfo.heading} />
            <h3>{singleInfo.heading}</h3>
          </Link>
        </div>
      ))}
    </div>
  );
};

export default PlaceDetail;

2. 路由配置匹配动态参数

将路由规则调整为支持动态参数的匹配模式:

// 路由配置示例
<Route path="/DetailsOfDestination/:destinationName" element={<DetailsOfDestination />} />

3. 详情页组件从路由参数取数,解决解构报错

修改DetailsOfDestination的取数逻辑,不再依赖外部传入的props,直接从路由参数匹配对应模拟数据,同时加入空值兜底避免解构报错:

import React from "react";
import { useParams } from "react-router-dom";
import FakeData from "../Fakedata/FakeData";

const DetailsOfDestination = () => {
  // 获取路由携带的动态参数
  const { destinationName } = useParams();
  // 匹配对应目的地数据,匹配失败时返回空对象做兜底
  const targetInfo = FakeData.find(item => item.heading === destinationName) || {};
  // 基于兜底后的空对象解构,不会触发undefined报错
  const { heading, img, text } = targetInfo;

  return (
    <div>
      <h1>{heading}</h1>
      <img src={img} alt={heading} />
      <p>{text}</p>
    </div>
  );
};

export default DetailsOfDestination;

通用兜底规则

后续如果遇到需要解构可能为空的对象属性的场景,可以在解构时加空值兜底:

const { heading, img } = props.singleInfo || {};

就算singleInfo为undefined,也只会渲染空值,不会触发运行时报错。


内容的提问来源于stack exchange,提问作者Shawal Anwar Chowdhury

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.26 14:24:04