React中渲染数组值如何避免map未定义及子元素错误?
问题背景
已从API获取到正确的数组数据,示例如下:
// API返回的正确数组数据 const myReturnedArray = [ { "id": "10001", "brand": "Best Brand", "center_name": "Best Brand Texas", "status": "Active", "emails": [ { "CreateDate": "October 12, 2022 at 10:59:09 AM UTC-5", "emailAddress": "test@test.com", "firstName": "Test", "lastName": "Tester", "id": "0eac8839-6e61-42f5-b55f-e2fa17b0262b", "licenseType": "Unlimited", "updateDate": "October 12, 2022 at 10:59:09 AM UTC-5", "userType": "STORE" } ], "licenses": [ { "CreateDate": "October 12, 2022 at 10:59:09 AM UTC-5", "licenseType": "STORE", "status": "ASSIGNED", "updatedBy": "SYSTEM", "updateDate": "October 12, 2022 at 10:59:09 AM UTC-5", "renewDate": "October 12, 2022 at 10:59:09 AM UTC-5", "expirationDate": "October 12, 2022 at 10:59:09 AM UTC-5", "id": "0eac8839-6e61-42f5-b55f-e2fa17b0262b" } ] } ]
想要在React的return语句中用<div>或<span>展示数组内对象的具体值,但遇到多个错误:
- 使用
map函数时,报错:"Objects are not valid as a React child (found: object with keys {id, brand, center_name, status, emails, licenses}). If you meant to render a collection of children, use an array instead."
- 直接调用
myReturnedArray.map(...)时,报错:myReturnedArray is undefined - 用
JSON.stringify(myReturnedArray)能正常渲染字符串,说明组件可访问数组,但无法正确展示内部内容。
期望的渲染效果示例:
return ( <> <span>your email is : test@test.com</span> <div> your first name is : Test </div> <span> your last name is : Tester </span> </> );
解决方案
1. 解决myReturnedArray未定义的问题
API请求是异步操作,组件初始化时数组可能还未获取到数据,必须先做空值判断:
// 方式1:用可选链操作符,安全调用map { myReturnedArray?.map(item => ...) } // 方式2:条件渲染,确认数组存在后再调用map { myReturnedArray && myReturnedArray.map(item => ...) } // 方式3:初始化状态时给数组默认值 const [myReturnedArray, setMyReturnedArray] = useState([]);
2. 正确渲染嵌套数据
数组内的每个元素是包含嵌套数组(emails)的对象,不能直接渲染整个对象,必须精准访问具体属性:
场景1:数组仅含单个元素
如果确定数组只有一条数据,可直接通过索引访问:
return ( <div> {myReturnedArray.length > 0 && ( <> <span>your email is : {myReturnedArray[0].emails[0].emailAddress}</span> <div> your first name is : {myReturnedArray[0].emails[0].firstName} </div> <span> your last name is : {myReturnedArray[0].emails[0].lastName} </span> </> )} </div> );
场景2:数组含多个元素
用map遍历数组,同时给每个子元素添加唯一key属性(避免唯一键警告):
return ( <div> {myReturnedArray?.map(center => ( <div key={center.id} className="center-item"> <h3>{center.center_name}</h3> <p>品牌:{center.brand}</p> <div className="email-list"> {center.emails?.map(email => ( <div key={email.id} className="email-item"> <span>邮箱:{email.emailAddress}</span> <div>名字:{email.firstName}</div> <span>姓氏:{email.lastName}</span> </div> ))} </div> </div> ))} </div> );
3. 核心注意事项
React无法直接渲染对象或数组,必须提取出字符串、数值等基础类型的属性再渲染,禁止直接写{item},要写{item.brand}这类具体属性。
内容的提问来源于stack exchange,提问作者evan
相关产品推荐
相关产品推荐

