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

React联系人应用动态访问对象属性出现Undefined问题求助

Fixing the Undefined Property Issue in Your Contact App

Hey there! Let's break down why those last two console logs are returning undefined and fix your contact app bug.

First, the Root Cause

Looking at your contacts.js file, each contact object only has these properties: name, imgURL, phone, and email. There's no such thing as infoDetails or type in any of your contact entries. That's why when you try to log contacts[props.id].infoDetails or contacts[props.id].type, you get undefined—those properties don't exist!

What You're Actually Trying to Do

It looks like you want to use the infoType prop to dynamically fetch the corresponding property from the contact object. For example, if infoType is "name", you want to get the contact's name; if it's "email", you want their email.

To do this, you need to use bracket notation instead of dot notation for accessing the property. Dot notation only works with fixed property names, but bracket notation lets you use variables (like your infoType prop) to access properties dynamically.

Fixed Details.jsx Code

Here's how to update your Details.jsx to make it work:

import React from "react";
import contacts from "../contacts.js";

function Details(props){
  const contact = contacts[props.id];
  const infoValue = contact[props.infoType]; // This is the key fix!

  console.log(props.infoType); // Should log "name" as expected
  console.log(contact); // Logs the full contact object
  console.log(contact.name); // Logs the contact's name
  console.log(infoValue); // Logs the value matching infoType (e.g., contact's name)

  return (
    <p className="info">{infoValue}</p> // Now displays the correct info
  )
}

export default Details;

Extra Tips

  • Make sure when you pass infoType to the Details component (like <Details id={props.id} infoType="email" />), the value matches one of the properties in your contact objects (name, phone, email). If you pass a value that doesn't exist (like "address"), you'll get undefined again—so stick to the properties defined in contacts.js.
  • You might want to add a fallback in case infoValue is undefined, to avoid broken UI. For example:
    return (
      <p className="info">{infoValue || "No info available"}</p>
    )
    

That should resolve your undefined property issue and let you dynamically display contact details based on the infoType prop!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 06:42:52