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

如何在React.js与JavaScript中将逗号分隔数组转为单独列表项?

解决方法:将数组转为独立的列表项

嘿,我来帮你把数组里的食材变成单独的列表项!问题出在你现在用toString()把数组转成了逗号分隔的字符串,所以所有食材都挤在一个<li>里了。我们可以直接遍历数组来生成每个独立的列表项,具体修改如下:

render(){ 
  const recipe = this.props.recipe; 
  // 去掉toString(),直接保留数组本身
  const recipeIngredients = recipe.ingredients; 
  return ( 
    <div> 
      <li>{recipe.recipeName}</li> 
      {/* 遍历数组,为每个食材生成独立的列表项 */}
      {recipeIngredients.map((ingredient, index) => (
        <li key={index}>{ingredient}</li>
      ))}
      <div> 
        <img src={recipe.smallImageUrls} alt="Recipe image"/> 
      </div> 
    </div> 
  ) 
}

关键说明:

  1. 移除toString():不再把数组转成字符串,直接使用原始数组进行遍历操作。
  2. 用map()遍历数组:map()方法会逐个处理数组里的元素,为每个食材生成一个独立的<li>标签。
  3. 添加key属性:React要求列表项必须有唯一的key值,这里用数组索引index作为临时方案(如果食材名称本身是唯一的,也可以直接用ingredient作为key)。

另外从HTML语义化角度,建议把所有<li>放在<ul>容器里,这样更符合规范,优化后的代码如下:

render(){ 
  const recipe = this.props.recipe; 
  const recipeIngredients = recipe.ingredients; 
  return ( 
    <div> 
      <ul>
        <li>{recipe.recipeName}</li> 
        {recipeIngredients.map((ingredient, index) => (
          <li key={index}>{ingredient}</li>
        ))}
      </ul>
      <div> 
        <img src={recipe.smallImageUrls} alt="Recipe image"/> 
      </div> 
    </div> 
  ) 
}

修改后页面就会显示成清晰的无序列表:

  • recipeName
  • jamaican rum
  • fresh lime juice
  • simple syrup
  • Angostura Aromatic Bitters

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:05:24