【问题标题】:React mapping over the same array but rendering different output在同一个数组上反应映射但呈现不同的输出
【发布时间】:2019-01-08 14:41:09
【问题描述】:

我有一种情况,我需要在我的渲染方法中映射同一个数组两次,以渲染数组中对象的不同属性。 所以,情况就是这样:

   <Row>
      <Column xs="12" md="6">
        <Row>
          <Column xs="12">
            <Undertekst>
              <FormattedMessage id="InfoPanel.PaymentDates" />
            </Undertekst>
          </Column>
        </Row>
        {getPeriods(payment.periods, periodsDates)}
      </Column>
      <Column xs="12" md="6">
        <Row>
          <Column xs="12">
            <Undertekst>
              <FormattedMessage id="InfoPanel.PaymentAmount" />
            </Undertekst>
          </Column>
        </Row>
        {getPeriods(payment.periods, amount)}
      </Column>
    </Row>

因此,由于我需要在两个位置映射同一个数组,我创建了一个函数,该函数接受一个数组和一个函数,该函数将从数组中的当前对象呈现子元素。

const periodsDates = period => `${moment(period .from).format(DDMMYYYY_DATE_FORMAT)} - ${moment(period .to).format(DDMMYYYY_DATE_FORMAT)}`;
const amount= period => formatCurrency(period.amount);
const getPeriods = (periods, children) => periods.map(period => (
  <Row>
    <Column xs="12">
      <Normaltekst>
        {children(period )}
      </Normaltekst>
    </Column>
  </Row>
));

我想知道这是否是解决这个问题的方法,还是有更好的方法来解决这个问题,如果可能的话,也许使用柯里化?

【问题讨论】:

    标签: arrays reactjs children


    【解决方案1】:

    您可以构建一个新的无状态组件,假设您将其称为带有 2 个道具(句点、数据)的句点。 这样您甚至可以在其他地方使用它。

    【讨论】:

    • 那是一样的,因为我会调用该组件两次,并且在数组上的映射量与我现在的相同。
    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 2021-05-29
    • 2020-04-30
    • 1970-01-01
    相关资源
    最近更新 更多