Next.js项目中使用GraphQL映射字段时触发TypeError错误求助
Let's break down why this error is happening and how to fix it step by step:
Root Cause
The error pops up because you're trying to run map() on profileData.profiles, but this property doesn't exist in your GraphQL response. Looking at your getProfiles.js query, the profiles array is nested inside businessInfo under the businessProfile object—your component is accessing the wrong path entirely!
Step 1: Correct the Field Path
Update your component to target the actual location of the profiles array in your data structure:
Instead of this:
{profileData.profiles.map((showProfile) => (...))}
Use this corrected path:
{profileData.businessInfo?.profiles?.map((showProfile) => ( <div key={showProfile.profile}> <h5> {showProfile.profile} </h5> </div> ))}
The ?. (optional chaining operator) acts as a safety net: if businessInfo or profiles is undefined or null, the code won't throw an error—it'll just skip rendering the mapped items.
Step 2: Add a Robust Fallback for Empty Arrays
To make this even more resilient, use the nullish coalescing operator (??) to default to an empty array if profiles is missing entirely. This ensures map() always has a valid array to work with:
{(profileData.businessInfo?.profiles ?? []).map((showProfile) => ( <div key={showProfile.profile}> <h5> {showProfile.profile} </h5> </div> ))}
Step 3: Verify Your GraphQL Response Structure
If you're still hitting issues, add a console.log in getStaticProps to inspect the actual data coming back from your API. This will help you confirm the structure matches what you expect:
export async function getStaticProps({ params }) { const data = await getProfiles(params.slug); console.log('GraphQL Response:', data); // Check this output in your terminal return { props: { profileData: data.businessProfile } }; }
Double-check that data.businessProfile.businessInfo.profiles is indeed an array (or exists at all). If it's missing, you may need to adjust your GraphQL query or verify your backend data setup.
Bonus: Handle Empty Profile Cases Gracefully
Add a conditional render to show a user-friendly message when there are no profiles to display:
<section> <Container> <Row> <Col lg={6} md={6} sm={6} xs={12}> {profileData.businessInfo?.profiles?.length ? ( profileData.businessInfo.profiles.map((showProfile) => ( <div key={showProfile.profile}> <h5> {showProfile.profile} </h5> </div> )) ) : ( <p>No profiles available for this business.</p> )} </Col> </Row> </Container> </section>
内容的提问来源于stack exchange,提问作者Adewale Perfect

