根据函数返回的内容渲染组件

时间:2021-03-04 14:10:11

标签: reactjs react-functional-component conditional-rendering

我有一个功能可以检查处方是否过期。我映射了一组处方并将它们显示在一个表格组件中。

如何仅在函数返回“Active”时显示组件?实现这个的语法是什么?

这是我的代码:

活动/过期检查功能

const datePrescription = (prescriptionDate, prescriptionExpirationDate) => {
    let prescriptionIssueDate = new Date(prescriptionDate)
    // add the days the prescription is meant to be active of to the original prescription date
    prescriptionIssueDate.setDate(prescriptionIssueDate.getDate() + prescriptionExpirationDate);
    // get current time
    let currentDate = new Date()

 // compare current date with expiration to determine if the prescription has expired
    if (currentDate > prescriptionIssueDate) {
      return "Expired"
    } else {
      return "Active"
    }
  }

组件:

<Table className={classes.table} aria-label="simple table">
    <TableHead>
      <TableRow>
        <TableCell><strong>Patient</strong></TableCell>
        <TableCell align="right"><strong>Patient Diagnosis</strong></TableCell>
        <TableCell align="right"><strong>Issuing Date</strong></TableCell>
        <TableCell align="right"><strong>Issuing Doctor</strong></TableCell>
        <TableCell align="right"><strong>Pharmaceutical Drug</strong></TableCell>
        <TableCell align="center"><strong>Action</strong></TableCell>
      </TableRow>
    </TableHead>
    <TableBody>
      {prescriptions.map((prescription) => (
    <Slide direction="up" in={prescriptions} mountOnEnter unmountOnExit>
    <TableRow key={prescription._id}>
          <TableCell>{prescription.name}</TableCell>
          <TableCell align="right">{prescription.diagnosis}</TableCell>
          <TableCell align="right">{new Date(prescription.prescriptionDate).toDateString()}</TableCell>
          <TableCell align="right">{prescription.doctor}</TableCell>
          <TableCell align="right">{prescription.drug}</TableCell>
          <TableCell align="center">
              <Tooltip title="Details">
                    <IconButton aria-label="details" component={Link} to={`/prescriptions/${prescription._id}`}>
                        <NoteAddIcon />
                     </IconButton>
                    </Tooltip> 
          </TableCell>
        </TableRow>
        </Slide>
      ))}
    </TableBody>
  </Table>

1 个答案:

答案 0 :(得分:1)

您应该过滤数组,然后将其映射到 JSX:

{
    prescriptions
        .filter((prescription) => {
            return datePrescription(
                prescription.prescriptionDate,
                prescription.prescriptionExpirationDate
            ) === 'Active';
        })
        .map((prescription) => (
            <Slide direction="up" in={prescriptions} mountOnEnter unmountOnExit>

            </Slide>
        ))
}