【问题标题】:How to render element only once in conditional rendering?如何在条件渲染中只渲染一次元素?
【发布时间】:2021-11-20 05:05:15
【问题描述】:
<ol className={classes.ol}>
      {props.data.definitions
        .sort((a, b) => a.partOfSpeech.localeCompare(b.partOfSpeech))
        .map((definition, index) => {
          return (
            <>
              <h3>{definition.partOfSpeech}</h3>
              <li key={index} className={classes.list}>
                {definition.definition.charAt(0).toUpperCase() +
                  definition.definition.slice(1)}{" "}
                ({definition.partOfSpeech})
              </li>
            </>
          );
        })}
    </ol>

上面是按字母顺序对“partofSpeech”进行排序并输出带有单词定义的词性的代码。如果词性相同,我试图只显示一次词性。当前输出如下所示。

是否可以在顶部仅显示一次词性并根据该词性呈现列表?我尝试使用 reduce 并比较对象的 partOfSpeech 仍然无法达到我想要的效果。

我想要达到的目标:

【问题讨论】:

  • 您可以使用 _.groupBy(props.data.definitions, def => def.partofSpeech) 对基于“partofSpeech”的数据进行分组; "groupBy" 是一个 lodash 函数,否则你也可以使用 reduce 来分组。您可以查看以下答案:stackoverflow.com/questions/40774697/…

标签: reactjs jsx conditional-rendering


【解决方案1】:

是的,这是可能的,但您必须更改您尝试映射的对象。目前定义的结构为

[{
  "definition": "located at or near the back of an animal",
  "partOfSpeech": "adjective"
}]

您想要的案例结构类似于:

[{
  "partOfSpeech": "adjective",
  "definitions": ["located at or near the back of an animal", "..."],  
}]
// or
[{
  "adjective": ["located at or near the back of an animal", "..."], 
  "adverb": ["in or to or toward a past time", "..."], 
}]

“定义” 也可以是数组中的对象,但关键是您需要先按属性分组,然后有两个迭代器。一个跨 partOfSpeech 和一个跨 “定义”

您可以使用Array 函数自己构建分组逻辑或使用lodash groubBy

// groups by property length
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }

有关如何分组的更多选项,您还可以查看How to group an array of objects by key

【讨论】:

  • 很遗憾,我无法更改结构,因为我是从外部 API 获取的。
  • 您仍然可以更改它,因为您在某处调用了 API。然后,您可以在获取响应后以任何您喜欢的方式转换/更改响应。
  • 您可以在将响应分配给反应组件的props之前转换响应
猜你喜欢
  • 2021-10-01
  • 1970-01-01
  • 2021-10-21
  • 2022-11-01
  • 2020-11-25
  • 2021-05-01
  • 2019-04-27
  • 2018-07-04
  • 1970-01-01
相关资源
最近更新 更多