首页 > 解决方案 > React JS 中循环内的条件渲染

问题描述

我有来自我试图在表格中显示的外部 API 的数据。数据带有日期时间戳。

我想在表格中呈现数据,但其中有一个额外的行显示日期更改时的日期。

我试过的


import React from 'react';
import { Link } from 'react-router-dom';
import { Table } from 'react-bootstrap';

import * as helpers from '../../common/helpers';

export default class SomeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null,
    };
  }

  componentDidMount() {
    fetch(`https://api.example.com`)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            data: result
          });
        }
      )
  }

  render() {
    const { data } = this.state;
    return (
      <>
        <h4>Most Recent</h4>
        <Table>
          <thead>
            <tr>
              <th>Time</th>
              <th>Column 1</th>
              <th>Column 2</th>
            </tr>
          </thead>
          <tbody>
            {data.map(newRow => (

              // Here I'd like to conditionally render a row if there has been a change in day from the last row before rendering the next row.
              // ie. if previousDate != currentDate
              // <tr>
              //   <td>{helpers.getFormattedDate(newRow.time)}</td>
              //   <td></td>
              //   <td></td>
              // </tr>
              // Then render the following :

              <tr key={newRow.id}>

                <td>
                  {helpers.getFormattedTime(newRow.time)}
                </td>

                <td>
                  <Link to={`/something`}>{helpers.getFormattedNumber(newRow.value)}</Link>
                </td>

                <td>
                  {/* Some more content here */}
                </td>

              </tr>
            ))}
          </tbody>
        </Table>

      </>
    );
  }
}

这里的任何帮助将不胜感激,我对此感到有点迷茫。

谢谢!

标签: reactjsloopsrendering

解决方案


你可以通过结合两个特性在 React 中进行条件渲染:

  1. 一旦可以确定表达式的值,JavaScript 就会停止使用布尔运算符(如&&和)对表达式求值。||例如,在 中,如果返回 false ( , , , ) 值,则永远不会调用func1() && func2()该函数。同样,如果返回真值,则永远不会调用 in 。func2func1nullundefinedfalse0func1() || func2()func2func1

  2. React 不会呈现虚假(除了0)值。

因此,在 React 中进行条件渲染的一种常见方法是执行以下操作:

<div>
    { isTrue && (
        <MyConditionalComponent/>
    )}
</div>

MyConditionalComponent只有在真实的情况下才会呈现在哪里isTrue

在您的情况下,由于您使用的是map,因此您可能还希望使用该Fragment组件,该组件基本上允许您为map. 或者,您可以使用 a reduce,但为简单起见,我将仅展示一个带有 的示例map

<tbody>
  {data.map((newRow, i) => (

    <React.Fragment>
      (i !== 0 && (getDate(newRow.time) !== getDate(data[i - 1].time))) && (
        <tr>
          <td>{helpers.getFormattedDate(newRow.time)}</td>
          <td></td>
          <td></td>
        </tr>
      )

      <tr key={newRow.id}>

        <td>
          {helpers.getFormattedTime(newRow.time)}
        </td>

        <td>
          <Link to={`/something`}>{helpers.getFormattedNumber(newRow.value)}</Link>
        </td>

        <td>
          {/* Some more content here */}
        </td>

      </tr>
    </React.Fragment>
  ))}
</tbody>

哪里getDate会有一些函数只返回Date对象的日期部分。

请注意,我们还使用回调的第二个参数 ( i) map,它是当前元素的索引,用于检查前一个元素的日期。


推荐阅读