React渲染map函数时出现Unexpected token等语法错误,求排查原因
问题原因与解决方案
错误原因
完全是语法问题导致的,核心有两个点:
- return语句的括号内多了一对多余的
{}:在React JSX里,return()用来直接返回JSX元素/表达式,你却把三元运算符整个用{}包起来了。{}的作用是在JSX内部嵌入JS表达式,但这里整个三元运算就是返回JSX的表达式,直接放在return()里就行,外层加{}会被引擎当成对象字面量解析,直接引发语法报错。 map方法的回调函数末尾漏写了闭合的),导致括号不匹配,触发第二个错误。
修正后的代码
{newMessages.map(function (item) { return ( userId === item.event.sender ? <div class="flex justify-start mb-4"> <div class="ml-2 py-3 px-4 bg-blue-400 rounded-br-3xl rounded-tr-3xl rounded-tl-xl text-white" > {item.event.content.body} </div> <img src="https://source.unsplash.com/vpOeXr5wmR4/600x600" class="object-cover h-8 w-8 rounded-full" alt="" /> </div> : <div class="flex justify-end mb-4"> <img src="https://source.unsplash.com/vpOeXr5wmR4/600x600" class="object-cover h-8 w-8 rounded-full" alt="" /> <div class="ml-2 py-3 px-4 bg-gray-400 rounded-br-3xl rounded-tr-3xl rounded-tl-xl text-white" > {item.event.content.body} </div> </div> ) })}
额外优化建议
用箭头函数能让代码更简洁,另外React里建议用className代替class(因为class是JavaScript关键字),优化后代码如下:
{newMessages.map(item => ( userId === item.event.sender ? <div className="flex justify-start mb-4"> <div className="ml-2 py-3 px-4 bg-blue-400 rounded-br-3xl rounded-tr-3xl rounded-tl-xl text-white"> {item.event.content.body} </div> <img src="https://source.unsplash.com/vpOeXr5wmR4/600x600" className="object-cover h-8 w-8 rounded-full" alt="" /> </div> : <div className="flex justify-end mb-4"> <img src="https://source.unsplash.com/vpOeXr5wmR4/600x600" className="object-cover h-8 w-8 rounded-full" alt="" /> <div className="ml-2 py-3 px-4 bg-gray-400 rounded-br-3xl rounded-tr-3xl rounded-tl-xl text-white"> {item.event.content.body} </div> </div> ))}
内容的提问来源于stack exchange,提问作者John Mordel
相关产品推荐
相关产品推荐

