Как переписать код, чтобы код реагировал на dry - PullRequest
2 голосов
/ 14 апреля 2020

Я относительно новичок в реакции и хотел знать, как я мог бы переписать этот код, чтобы он стал dry. Как вы можете видеть, содержание карты и типография практически одинаковы, но единственное отличие состоит в <Typography color="textSecondary" gutterBottom> и <Typography variant="body2" component="p">

  <div className={styles.container}>
      <Grid container spacing={3} justify="center">
        <Grid item component={Card} xs={12} md={3} className={cx(styles.card, styles.infected)}>
          <CardContent>
            <Typography color="textSecondary" gutterBottom>
              Infected
            </Typography>
            <Typography variant="h5" component="h2">
              <CountUp
                start={0}
                end={confirmed.value}
                duration={2.5}
                separator=","
              />
            </Typography>
            <Typography color="textSecondary">
              {new Date(lastUpdate).toDateString()}
            </Typography>
            <Typography variant="body2" component="p">
              Number of active cases of COVID-19
            </Typography>
          </CardContent>
        </Grid>
        <Grid item component={Card} xs={12} md={3} className={cx(styles.card, styles.recovered)}>
          <CardContent>
            <Typography color="textSecondary" gutterBottom>
              Recovered
            </Typography>
            <Typography variant="h5" component="h2">
              <CountUp
                start={0}
                end={recovered.value}
                duration={2.75}
                separator=","
              />
            </Typography>
            <Typography color="textSecondary">
              {new Date(lastUpdate).toDateString()}
            </Typography>
            <Typography variant="body2">
              Number of recoveries from COVID-19
            </Typography>
          </CardContent>
        </Grid>
        <Grid item component={Card} xs={12} md={3} className={cx(styles.card, styles.deaths)}>
          <CardContent>
            <Typography color="textSecondary" gutterBottom>
              Deaths
            </Typography>
            <Typography variant="h5" component="h2">
              <CountUp
                start={0}
                end={deaths.value}
                duration={2.75}
                separator=","
              />
            </Typography>
            <Typography color="textSecondary">
              {new Date(lastUpdate).toDateString()}
            </Typography>
            <Typography variant="body2">
              Number of deaths caused by COVID-19
            </Typography>
          </CardContent>
        </Grid>
      </Grid>
    </div>

1 Ответ

0 голосов
/ 14 апреля 2020

Вы можете просто нанести карту вокруг данных, чтобы отобразить Grid-> Card-> Typography Components, предполагая, что вы можете извлечь данные и сохранить их в своем состоянии или пропустить через подпорки. В любом случае все в порядке.

const data = [{
  type: 'infected',
  displayName: 'Infected',
  count: {
    start: 0
  },
  duration: 2.5,
  displayStatusText: 'Number of active cases of COVID-19',
},
{
  type: 'recovered',
  displayName: 'Recovered',
  count: {
    start: 0
  },
  duration: 2.5,
  displayStatusText: 'Number of recoveries from COVID-19',
},
{
  type: 'infected',
  displayName: 'Infected',
  count: {
    start: 0
  },
  duration: 2.5,
  displayStatusText: 'Number of deaths caused by COVID-19',
}];

И в ответ на метод рендеринга вы можете сопоставить компонент следующим образом

render() {
    return (
      <div className={styles.container}>
        <Grid container spacing={3} justify="center">
          {this.state.data.map((item, i) => {
            return (
              <Grid key={i} item component={Card} xs={12} md={3}
                className={cx(styles.card, item.type === 'infected' ? styles.infected : item.type === 'recovered' ? styles.recovered : styles.deaths)}>
                <CardContent>
                  <Typography color="textSecondary" gutterBottom>
                    {item.type}
                  </Typography>
                  <Typography variant="h5" component="h2">
                    <CountUp start={item.count.start} end={item.type === 'infected' ? confirmed.value : item.type === 'recovered' ? recovered.value : deaths.value} duration={item.duration} separator="," />
                  </Typography>
                  <Typography color="textSecondary">
                    {new Date(lastUpdate).toDateString()}
                  </Typography>
                  <Typography variant="body2" component="p">
                    {item.displayStatusText}
                  </Typography>
                </CardContent>
              </Grid>
            );
          })}
        </Grid>
      </div>
    )
  }

Единственный улов здесь - вы должны заметить, как className и конечные атрибуты получают значения на основе оценки троичного оператора.

...