React条件渲染出现Unexpected token错误,循环渲染元素失败
解决React组件中for循环渲染元素的Unexpected token错误
问题原因
JSX中的大括号{}仅支持表达式(能返回值的代码),而for循环是语句(无返回值的执行逻辑),直接将for循环放入大括号内会触发语法错误。
修复方案
方案1:使用Array.map()生成列表项
通过创建一个包含4个元素的数组,再用map遍历生成对应的<li>元素:
import React from 'react'; function MacroCategory(props) { const targetLevel = props.macrocategory_score.macroDescription.level; return ( <> <table> <thead> <tr> <th>CATEGORY</th> <th>DESCRIPTION</th> <th>RESULTS</th> </tr> </thead> <tbody> <tr> <td> <ul className="onePage_bar"> {Array.from({ length: 4 }, (_, index) => { const i = index + 1; return ( <li key={i} className={i < targetLevel ? "onePage_level-0" : `onePage_level-${props.level}`} ></li> ); })} </ul> </td> </tr> </tbody> </table> </> ) } export default MacroCategory;
方案2:预先生成列表项数组
在组件内部先通过for循环将所有<li>元素存入数组,再在JSX中渲染该数组:
import React from 'react'; function MacroCategory(props) { const listItems = []; const targetLevel = props.macrocategory_score.macroDescription.level; for(let i = 1; i <=4; i++){ listItems.push( <li key={i} className={i < targetLevel ? "onePage_level-0" : `onePage_level-${props.level}`} ></li> ); } return ( <> <table> <thead> <tr> <th>CATEGORY</th> <th>DESCRIPTION</th> <th>RESULTS</th> </tr> </thead> <tbody> <tr> <td> <ul className="onePage_bar"> {listItems} </ul> </td> </tr> </tbody> </table> </> ) } export default MacroCategory;
关键注意点
- 必须给每个列表项添加
key属性,帮助React识别列表元素的变化,提升渲染性能。 - 提取重复使用的变量(如
targetLevel)可提升代码可读性和维护性。
内容的提问来源于stack exchange,提问作者fg_st
相关产品推荐
相关产品推荐

