在 map 中使用 if 条件渲染 React JSX 的问题

Issue with rendering React JSX using if conditional inside map

情况 1) 我正在尝试使用地图和三元运算符有条件地进行渲染。在这里,我迭代了一个对象数组,然后只渲染其中的前六个。试图实现相同的目标,但它似乎并不奏效。

不胜感激

对象

const recentEventsData = [
  { key: "01", text: "AAA", timestamp: "11:52:27:02 02-11-2019" },
  { key: "02", text: "BBB", timestamp: "11:52:29:02 02-11-2019" },
  { key: "03", text: "CCC", timestamp: "11:52:30:02 02-11-2019" }
];

内部渲染()

{
  recentEventsData.map((data, index) => {
    {
      index < 6 ? (
        <div key={index}>
          //Want the transformed output here , that is fourth value from object
          <p>{data.text}</p>
          <p>{data.timestamp}</p>
          <hr />
        </div>
      ) : null;
    }
  });
}

您应该 return 使用 return 关键字的值。

使用 splice 并删除内部 {} 括号,因为 .map() 需要 return 值才能工作。

The splice() method adds/removes items to/from an array, and returns the removed item(s).

{
  recentEventsData.slice(0, 6).map((data, index) => (
        <div key={index}>
          <p>{data.text}</p>
          <p>{data.timestamp}</p>
          <hr />
        </div>
      )
  );
}

当你想注入一个JavaScript表达式时,你只需要在JSX中使用{},所以在给定map的函数内部不需要创建一个新的块.

既然你已经给了函数一个主体,你还需要明确地return结果。

{recentEventsData.map((data, index) => {
  return index < 6 ? (
    <div key={index}>
      <p>{data.text}</p>
      <p>{data.timestamp}</p>
      <hr />
    </div>
  ) : null;
})}

无需检查索引并 returning null 其余元素,您可以 slice 在使用 [=13= 之前找出您感兴趣的元素].

{recentEventsData.slice(0, 6).map((data, index) => (
  <div key={index}>
    <p>{data.text}</p>
    <p>{data.timestamp}</p>
    <hr />
  </div>
))}