ReactJS与GatsbyJS组件中const无法渲染,请求技术协助
Hey there! Let’s get to the bottom of why your contents array isn’t showing up in your component. I’ve helped folks work through this exact issue plenty of times, so let’s break it down with clear examples and common pitfalls to check.
First, Here’s a Working Example
Let’s start with a complete component that correctly renders your contents array. This should give you a baseline to compare against your code:
import React from "react" const ContentSection = () => { // Your existing contents array const contents = [ { title: "Allier design et performance, c'est possible", chapo: "Les meilleures technologies au service de votre site web." }, { title: "Nouvel ère : les application web progressives", chapo: "Pour des sites web accessibles en t..." } ] return ( <div className="content-grid"> {/* The critical part: mapping over the array and returning JSX */} {contents.map((contentItem, index) => ( <article key={index} className="content-card"> <h2>{contentItem.title}</h2> <p>{contentItem.chapo}</p> </article> ))} </div> ) } export default ContentSection
Common Issues That Cause This Problem
Let’s go through the most likely reasons your array isn’t rendering:
Forgot to return JSX in
map()
If you’re using curly braces{}insidemap()without areturnstatement, React won’t get any JSX to render. For example:// ❌ This won't work - no return! contents.map(item => { <div>{item.title}</div> }) // ✅ Fix 1: Add return contents.map(item => { return <div>{item.title}</div> }) // ✅ Fix 2: Use parentheses for implicit return contents.map(item => ( <div>{item.title}</div> ))Missing the
keyprop
React requires a uniquekeyprop for every item in a mapped list to optimize re-renders. While usingindexworks for static arrays like yours, if you ever add/remove items later, it’s better to use a unique ID from your data (if available). Without a key, you might see warnings in the console, and the list might not render correctly.Not embedding the mapped result in your JSX
Make sure the entirecontents.map(...)call is placed inside the JSX returned by your component. If you’re running it outside thereturnblock or not including it in the rendered output, it won’t show up on the page.Array is empty or undefined (less likely here, but worth checking)
If yourcontentsarray was being fetched asynchronously (e.g., from a GraphQL query in Gatsby), you might need to add a loading state or check if the array exists before mapping. For your static array, this shouldn’t be an issue, but it’s a good habit to build:{contents ? contents.map(...) : <p>Loading content...</p>}
Double-Check Your Code
Compare your component against the working example above. Chances are, one of these small oversights is causing the issue. If you’re still stuck, feel free to share a snippet of your actual component code, and I can help narrow it down further!
内容的提问来源于stack exchange,提问作者user7388854

