首页 > 解决方案 > API 数组问题

问题描述

这是 API 响应:

{
  "meals": [
    {
      "strTags":"Fish,Breakfast,DateNight",
    }
  ]
}

我想看到以下结果:

在此处输入图像描述

这是我的代码:

<div>
  {recipe.strTags ? <Chip label={recipe.strTags.split(",")} /> : null}
</div>

现在它看起来像这样:

在此处输入图像描述

我怎样才能做到这一点?

标签: javascriptreactjsecmascript-6material-ui

解决方案


您需要拆分字符串以创建数组,然后使用map对其进行迭代以创建每个标签。请记住添加key属性以避免重新渲染问题。

解决方案:

<div>
  {
     recipe.strTags
        ? recipe.strTags
                .split(',')
                .map(label => (
                   <Chip label={label} key={label} />
                ))
        : null
  }
</div>

推荐阅读