Array.prototype.map()期望箭头函数回调返回值的报错问题及React代码修复问询
Hey there! Let's break down why you're seeing that "Map方法期望箭头函数回调返回值(Array.prototype.map()期望箭头函数回调返回值)" error in your UsersList component, and fix it right away.
问题原因
The issue lies in your map callback function: when you wrap the arrow function's code in curly braces {}, you need to explicitly use the return statement to send back the JSX element. Without it, the function returns undefined by default, which map doesn't recognize as a valid array item—hence the error.
修复方案
You have two simple ways to fix this:
方案1:添加显式的return语句
Just add return before your <li> element inside the curly braces to explicitly return the JSX:
import React from 'react'; const UsersList = (props) => { return( <ul> {props.Users.map((user)=> { // 添加return语句明确返回JSX元素 return <li> {user.name} {user.age} </li> })} </ul> ); } export default UsersList;
方案2:去掉大括号,使用箭头函数的隐式返回
If you don't need any extra logic inside the map callback, you can omit the curly braces entirely. Arrow functions without braces automatically return the expression that follows them:
import React from 'react'; const UsersList = (props) => { return( <ul> // 去掉大括号,让箭头函数隐式返回<li>元素 {props.Users.map((user)=> <li> {user.name} {user.age} </li>)} </ul> ); } export default UsersList;
额外小提示
To avoid potential errors if props.Users is ever undefined or null, you can add a quick check:
// 使用可选链操作符(推荐) {props.Users?.map((user)=> <li> {user.name} {user.age} </li>)} // 或者先判断是否为有效数组 {props.Users && props.Users.map((user)=> <li> {user.name} {user.age} </li>)}
内容的提问来源于stack exchange,提问作者Sardar Ahmed Khan

