JavaScript中使用map方法出现',' expected语法错误求助
语法错误修复方案
你代码里存在3处问题,直接触发,预期报错的是map方法缺少闭合括号,具体问题和修复方式如下:
Array.map()调用未补全闭合右括号),回调函数逻辑结束后需要添加右括号闭合map方法。
- map的箭头回调语法不规范:使用大括号
{}包裹函数体时必须显式写return指定返回内容;如果无额外计算逻辑,可直接去掉大括号使用隐式返回简化写法。
- map的箭头回调语法不规范:使用大括号
- 列表渲染的元素未绑定唯一
key属性,React会抛出列表渲染警告,建议补充key属性。
- 列表渲染的元素未绑定唯一
修复后可运行代码
class Products extends Component { constructor() { super(); this.state = { cart: [] } } render () { const { products } = this.props; return ( <> <thead> <th scope="col"><strong>Name</strong></th> { // 简化写法:去掉大括号和return,使用隐式返回 products.map((product, key) => <th key={key}>{product.title}</th>) } </thead> </> ) } }
如果需要在回调中写额外逻辑,保留大括号的写法如下:
products.map((product, key) => { // 这里可以加其他计算逻辑 return <th key={key}>{product.title}</th> })
内容的提问来源于stack exchange,提问作者Shpongle
相关产品推荐
相关产品推荐

