Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React JS中循环内的条件渲染_Reactjs_Loops_Rendering - Fatal编程技术网

Reactjs React JS中循环内的条件渲染

Reactjs React JS中循环内的条件渲染,reactjs,loops,rendering,Reactjs,Loops,Rendering,我有来自外部API的数据,我正试图在表中显示这些数据。数据返回时带有日期时间戳 我希望在表中呈现数据,但其中有一行显示日期更改时的日期 我试过的 我已尝试更新lastDate属性值 我已尝试使用(条件)进行条件渲染?应为:render()方法中的其他语法和变量 我不知道如何跟踪当前日期变量并在每次循环迭代中更新它 我尝试过将DateRow和DataRow拆分为单独的组件并传递日期,但状态没有持久化 我不确定这样做的最佳实践是什么。或者这只是个坏主意 从“React”导入React; 从'r

我有来自外部API的数据,我正试图在表中显示这些数据。数据返回时带有日期时间戳

我希望在表中呈现数据,但其中有一行显示日期更改时的日期

我试过的

  • 我已尝试更新lastDate属性值
  • 我已尝试使用(条件)进行条件渲染?应为:render()方法中的其他语法和变量
  • 我不知道如何跟踪当前日期变量并在每次循环迭代中更新它
  • 我尝试过将DateRow和DataRow拆分为单独的组件并传递日期,但状态没有持久化
  • 我不确定这样做的最佳实践是什么。或者这只是个坏主意

从“React”导入React;
从'react router dom'导入{Link};
从'react bootstrap'导入{Table};
从“../../common/helpers”导入*作为帮助程序;
导出默认类SomeComponent扩展React.Component{
建造师(道具){
超级(道具);
此.state={
数据:空,
};
}
componentDidMount(){
取回(`https://api.example.com`)
.then(res=>res.json())
.那么(
(结果)=>{
这是我的国家({
数据:结果
});
}
)
}
render(){
const{data}=this.state;
返回(
最近的
时间
第1栏
第2栏
{data.map(newRow=>(
//在这里,如果在渲染下一行之前,上一行的日期发生了变化,我希望有条件地渲染一行。
//即,如果上一个日期!=当前日期
// 
//{helpers.getFormattedDate(newRow.time)}
//   
//   
// 
//然后渲染以下内容:
{helpers.getFormattedTime(newRow.time)}
{helpers.getFormattedNumber(newRow.value)}
{/*此处有更多内容*/}
))}
);
}
}
任何帮助都将不胜感激,我对这一点有点迷茫


谢谢

您可以通过组合两个功能在React中执行条件渲染:

  • 一旦可以确定表达式的值,JavaScript就会停止使用布尔运算符(如
    &&
    |
    )计算表达式。例如,在
    func1()&&func2()
    中,如果
    func1
    返回假值(
    null
    undefined
    false
    0
    ),则永远不会调用函数
    func2
    。类似地,在
    func1()| | func2()
    中,如果
    func1
    返回真实值,则永远不会调用
    func2

  • React不会呈现错误的值(除了
    0

  • 因此,在React中执行条件渲染的常用方法是执行以下操作:

    
    {isTrue&&(
    )}
    
    其中,
    MyConditionalComponent
    仅在
    isTrue
    为真时才会呈现

    在您的例子中,由于您使用的是
    映射
    ,您可能还希望使用
    片段
    组件,它基本上允许您为
    映射
    的一个元素返回多个组件。或者,您可以使用
    reduce
    ,但为了简单起见,我将仅展示一个
    映射的示例:

    
    {data.map((newRow,i)=>(
    (i!==0&&(getDate(newRow.time)!==getDate(data[i-1].time))&&(
    {helpers.getFormattedDate(newRow.time)}
    )
    {helpers.getFormattedTime(newRow.time)}
    {helpers.getFormattedNumber(newRow.value)}
    {/*此处有更多内容*/}
    ))}
    
    其中,
    getDate
    是一个函数,它只从
    date
    对象返回日期部分


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

    您可以通过组合两个功能在React中执行条件呈现:

  • 一旦可以确定表达式的值,JavaScript就会停止使用布尔运算符(如
    &&
    |
    )计算表达式。例如,在
    func1()&&func2()
    中,如果
    func1
    返回假值(
    null
    undefined
    false
    0
    ),则永远不会调用函数
    func2
    。类似地,在
    func1()| | func2()
    中,如果
    func1
    返回真实值,则永远不会调用
    func2

  • React不会呈现错误的值(除了
    0

  • 因此,在React中执行条件渲染的常用方法是执行以下操作:

    
    {isTrue&&(
    )}
    
    其中,
    MyConditionalComponent
    仅在
    isTrue
    为真时才会呈现

    在您的例子中,由于您使用的是
    映射
    ,您可能还希望使用
    片段
    组件,它基本上允许您为
    映射
    的一个元素返回多个组件。或者,您可以使用
    reduce
    ,但为了简单起见,我将仅展示一个
    映射的示例:

    
    {data.map((newRow,i)=>(
    (i!==0&&(getDate(newRow.time)!==getDate(data[i-1].time))&&(
    {helpers.getFormattedDate(newRow.time)}
    
    
    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>
    
          </>
        );
      }
    }
    
    
    {data.map((newRow, index) => {
      const prevRow = data[index - 1];
      return (
        // Fragment is necessary because you will
        // now potentially render 2 elements
        <React.Fragment key={newRow.id}> 
          {prevRow && newRow.date !== prevRow.date && (
            <tr>
              <td>{helpers.getFormattedDate(newRow.time)}</td>
              <td></td>
              <td></td>
            </tr>
          )} 
          <tr>
            // The rest of your component
          </tr>
        <React.Fragment>
      )
    }}