You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Array.prototype.map()期望箭头函数回调返回值的报错问题及React代码修复问询

解决React中Array.prototype.map()箭头函数无返回值的错误

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:57:48