首页 > 解决方案 > 如何制作过滤和映射特定数据以从数据库中的对象呈现的函数方法

问题描述

在我的 React 应用程序中,我需要获取一些数据,并且从这些数据中我得到一些称为事件的东西。

与此类似

[
  {
    "id": "36",
    "ownerId": "",
    "ownerType": "",
    "title": "",
    "body": null,
    "type": "APPOINTMENT_SLOT",
    "typeId": null,
    "startTime": "2020-10-20T09:00:00.000Z",
    "endTime": "2020-10-30T15:00:00.000Z",
    "status": "CREATED",
    "actors": null,
    "eventTemplateId": "8",
    "timezone": null,
    "activeInfo": {
      "active": true,
      "startsIn": 1359,
      "endsIn": 13400,
      "__typename": "EventActiveInfo"
    },
    "__typename": "Event"
  },
  {
    "id": "99",
    "ownerId": "",
    "ownerType": "PARTICIPANT",
    "title": "",
    "body": null,
    "type": "APPOINTMENT_SITE",
    "typeId": "123",
    "startTime": "2020-10-22T08:00:00.000Z",
    "endTime": "2020-10-22T09:00:00.000Z",
    "status": "BOOKED",
    "actors": null,
    "eventTemplateId": "4",
    "timezone": "Europe/Stockholm",
    "activeInfo": {
      "active": false,
      "startsIn": -1461,
      "endsIn": 1520,
      "__typename": "EventActiveInfo"
    },
    "__typename": "Event"
  },
]

从上面我需要先从 ownerId 过滤以下部分的特定数据

我最初所做的是创建一个过滤器方法

events.filter(
      event =>
        event.ownerId === participant.studyId &&
        event.ownerType === 'PARTICIPANT' &&
        event.type === 'APPOINTMENT_SLOT' &&
        event.startTime,
    );

我需要实现的是,我从新过滤的部分获取了即将到来的 APPOINTMENT_SLOT 的最新数据,现在是 endTime。从这里我必须呈现一个包含文本和事件 ID 的按钮,并且当事件完成并获取下一个事件的 ID 时,该 ID 会发生变化。

举个例子:

事件 1 是从 20 Okt 到 28 Okt,按钮应显示为

appointments {APPOINTMENT_SLOT ID}

APPOINTMENT_SLOT ID 是即将发生的事件/实际事件。

事件 2 将相同,但当事件 1 完成时,将显示事件 2 的 ID,依此类推

我的问题是正确地制作这部分,因为我是新来的反应并且不确定最好的方法我尝试了 useEffect 作为另一个代码中的示例

useEffect(() => {
    if (Array.isArray(events)) {
      const _appointmentSlots = events
        .filter(
          event =>
            event.ownerId === participant.studyId &&
            event.ownerType === 'PARTICIPANT' &&
            event.type === 'APPOINTMENT_SLOT',
        )
        .map(event => ({
          id: event.id,
          title: event.title,
          start: formatDate(event.startTime),
          end: formatDate(event.endTime),
        }));
      console.log('App_slots', _appointmentSlots);
      setAppointmentSlots(_appointmentSlots);
    }
  }, [events]);

标签: javascriptreactjs

解决方案


推荐阅读