React新手开发小应用遇报错求助:代码无语法提示但运行出错
Hey there! Let's fix your CardList component step by step—those sneaky runtime errors can be tricky when there's no obvious syntax issue. Here are the problems in your code and how to resolve them:
1. Wrong React Import Syntax
You've got a typo in your React import. React is exported as a default export from the react package, so you don't need curly braces, and the package name should be in quotes.
Fix:
Change this:
import React from { react }
To this:
import React from 'react'
2. Missing Return in the map() Callback
Your robots.map() function isn't returning the <Card> component! When you use curly braces {} in an arrow function, you have to explicitly use return to send back the JSX. Alternatively, you can use parentheses () for implicit return (cleaner for JSX).
Also, you don't need to use robots[i]—the first parameter of the map callback (user) is already the current element in the array, so you can use that directly for cleaner code.
Fix either of these ways:
Option 1 (explicit return):
{ robots.map((user, i) => { return <Card key={i} id={user.id} name={user.name} email={user.email} /> }) }
Option 2 (implicit return, recommended for JSX):
{ robots.map((user) => ( <Card key={user.id} id={user.id} name={user.name} email={user.email} /> )) }
3. Bonus: Best Practice for key Prop
While using the index i as a key works for static lists, React recommends using a unique, stable identifier from your data (like user.id) instead. This helps React efficiently update the DOM when your list changes (e.g., adding/removing items).
Full Corrected Code
Here's the fixed version of your component:
import React from 'react' import Card from "./Card" const CardList = ({ robots }) => { return ( <div> { robots.map((user) => ( <Card key={user.id} id={user.id} name={user.name} email={user.email} /> )) } </div> ) } export default CardList
The reason you didn't see a syntax error is because these are runtime issues—your code is syntactically valid, but it doesn't behave as React expects (like not returning JSX or importing React incorrectly).
内容的提问来源于stack exchange,提问作者Varnit Rohilla

