如何使用 React 列出表中的元素?

我是反应新手。如何使用“map”函数在两列中列出两个不同数组的元素?


state = {

  dates: ["2000", "2001", "2002"],

  cases: ["1", "2", "3"]

}


render() {

  return (

    <thead>

      <tr>

        <th>Date</th>

        <th>Cases</th>

      </tr>

    </thead>

    <tbody>

      {this.state.dates.map(el => 

        <tr>

          <td>{el}</td>

        </tr>

      )} // I want to list elements from "cases" array like this but in the second column

    </tbody>

  )

}


慕莱坞森
浏览 69回答 2
2回答

米脂

快速简单的解决方案: 不推荐如果你总是假设dates和cases总是相同的长度,那么你可以这样做:{this.state.dates.map((el, index) => (&nbsp; <tr>&nbsp; &nbsp; <td>{this.state.dates[index]}</td>&nbsp; &nbsp; <td>{this.state.cases[index]}</td>&nbsp; </tr>))}该方法利用了函数index的参数map。然后您可以访问指定索引处的数组。推荐解决方案:通常的做法是按记录对数据进行分组。使用您的示例,使用如下结构:state&nbsp; = {&nbsp; records: [&nbsp; &nbsp; { date: '2000', caseId: '1' },&nbsp; &nbsp; { date: '2001', caseId: '2' },&nbsp; &nbsp; { date: '2002', caseId: '3' }&nbsp; ],}然后像这样实现它:{this.state.records.map(({ date, caseId }) => (&nbsp; <tr>&nbsp; &nbsp; <td>{date}</td>&nbsp; &nbsp; <td>{caseId}</td>&nbsp; </tr>))}我使用caseIdnot 来代替,case因为它case是 JavaScript 中语句的保留字switch。

慕尼黑的夜晚无繁华

您可以使用index映射函数中的参数并访问案例数组<tbody>&nbsp; {this.state.dates.map((el, index) => (&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>{el}</td>&nbsp; &nbsp; &nbsp; <td>{this.state.cases[index]}</td>&nbsp; &nbsp; </tr>&nbsp; ))}{" "}</tbody>;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5