如何在React组件的map循环内筛选渲染type为CONTACT的关联用户?
Absolutely! You’ve got two simple, effective ways to make this happen—either filter your array before running the map, or add a condition directly inside the map function. Let’s walk through both options:
Option 1: Filter First, Then Map (Recommended)
This is the cleaner approach because you narrow down your dataset to only the items you need before starting the loop. It’s more readable and avoids unnecessary iterations over items you don’t want to render:
type RelatedUser = { firstName: string, lastName: string, id: string, phoneNumber: string }; // Optional: Use a union type for stricter type safety type RelationType = "FRIEND" | "CONTACT"; export const ContactList: React.FunctionComponent<UserProps> = ({ data }) => { if (!data) return null; // Filter to keep only CONTACT relationships const contactRelations = data.users.nodes[0].userRelations.filter( (item: { relatedUser: RelatedUser; type: RelationType }) => item.type === "CONTACT" ); return ( <View style={styles.users}> {contactRelations.map((item) => { const userName = `${item.relatedUser.firstName} ${item.relatedUser.lastName}`; return ( <View style={styles.item} key={item.relatedUser.id}> <Text style={styles.userName}>{userName}</Text> </View> ); })} </View> ); };
Option 2: Add Condition Inside the Map
If you’d rather handle the check directly in the map function, you can return null for non-CONTACT items (React automatically ignores null when rendering):
type RelatedUser = { firstName: string, lastName: string, id: string, phoneNumber: string }; type RelationType = "FRIEND" | "CONTACT"; export const ContactList: React.FunctionComponent<UserProps> = ({ data }) => { if (!data) return null; return ( <View style={styles.users}> {data.users.nodes[0].userRelations.map( (item: { relatedUser: RelatedUser; type: RelationType }) => { // Skip rendering if this isn't a CONTACT if (item.type !== "CONTACT") return null; const userName = `${item.relatedUser.firstName} ${item.relatedUser.lastName}`; return ( <View style={styles.item} key={item.relatedUser.id}> <Text style={styles.userName}>{userName}</Text> </View> ); } )} </View> ); };
Quick Fix for Your Original Code
Your commented-out if (item.type: "CONTACT") had invalid syntax—we use === for equality checks in JavaScript/TypeScript, not a colon.
I’d lean toward Option 1 because it keeps your map function focused solely on rendering logic, rather than mixing in filtering. It also makes it easier to debug exactly which items are being processed!
内容的提问来源于stack exchange,提问作者user13101751

