React联系人应用动态访问对象属性出现Undefined问题求助
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
infoTypeto theDetailscomponent (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 getundefinedagain—so stick to the properties defined incontacts.js. - You might want to add a fallback in case
infoValueis 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

