【问题标题】:React JS: Only map certain elements of an array within JSX tag, where the elements to map are iteratedReact JS:仅在 JSX 标签内映射数组的某些元素,其中要映射的元素是迭代的
【发布时间】:2020-07-25 22:13:21
【问题描述】:

我使用以下代码在 React 中以编程方式创建了上表:

tableRenderer() {

    let table = <Table striped bordered hover responsive="sm" id='mytable'>
        <thead>
        <tr>
            {this.state.headers.map((header, index) =>
                <th key={index}>{header} </th>
            )}
        </tr>
        </thead>

            {this.state.timeLabels.map((label, index)=>
                <tr key={index}>   <td><b>{label} </b></td>
                    {this.state.table.slice(0,4).map((match, index)=>
                        <td key={index}>{match.teamA} vs {match.teamB}</td>
                    )}
                </tr> )}
                </Table>;

但是我被困在我需要的最后一个功能上:如何更改表格数组切片的值,所以在第一次运行时它切片 0-> 音高数,第二次运行音高数-> 音高数+音高数...等。 我是否需要创建一些函数来在每次创建行时迭代一个变量?

【问题讨论】:

    标签: arrays reactjs mapping


    【解决方案1】:

    大概是这样的:

    {this.state.timeLabels.map((label, index)=> {
      const NO_OF_PITCHES = 4;
      let from = NO_OF_PITCHES * index;
      let to = NO_OF_PITCHES * (index + 1);
    
      return <tr key={index}>
        <td><b>{label}</b></td>
        {this.state.table.slice(from,to).map((match, index)=>
          <td key={index}>{match.teamA} vs {match.teamB}</td>
        )}
      </tr>)}
    } 
    

    假设切片是 0,4... 4,8... 8,12... 等等

    您也可以将 NO_OF_PITCHES 提升到 map 函数的父级,因为不必在每次迭代时重新创建它

    【讨论】:

    • 谢谢,这工作我只需要编辑添加一个返回值。
    猜你喜欢
    • 2021-05-20
    • 1970-01-01
    • 2020-09-14
    • 2020-09-25
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    相关资源
    最近更新 更多