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

React中map箭头函数生成列表项正常,普通参数函数写法失效求助

React中map方法使用普通函数生成列表失效的原因及修复

你的普通函数写法里存在三个关键问题,导致无法正常渲染列表:

  • 缺少显式return语句:箭头函数在单表达式场景下会自动返回结果,但普通函数必须用return明确返回JSX元素,否则map的回调函数默认返回undefined,最终生成的数组全是无效值,渲染不出内容。
  • 参数名不匹配:回调函数的参数是frt,但你在key属性里写成了fruit.id,fruit这个变量在当前作用域不存在,会触发引用错误。
  • 变量名拼写错误:你定义的列表变量是fruitslist,但return时用的是fruitlist,变量名不匹配导致渲染的是未定义的变量。

修正后的代码

function List() {
    const fruits = [
        { id: 1, name: 'orange', calories: 67 },
        { id: 2, name: 'banana', calories: 63 },
        { id: 3, name: 'pineapple', calories: 87 },
        { id: 4, name: 'coconut', calories: 69 },
        { id: 5, name: 'kiwi', calories: 56 },
        { id: 6, name: 'guava', calories: 36 }
    ]

    let fruitslist = fruits.map(function (frt) {
        // 显式return JSX元素,同时使用正确的参数名frt
        return <li key={frt.id}>{frt.name} {frt.calories}</li>
    })
    // 使用正确的变量名fruitslist
    return (<ol>{fruitslist}</ol>)
}

export default List

内容的提问来源于stack exchange,提问作者rohan saka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 17:13:12