亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

慕萊塢森 2023-12-11 16:11:23
我是反應新手。如何使用“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>  )}
查看完整描述

2 回答

?
米脂

TA貢獻1836條經驗 獲得超3個贊

快速簡單的解決方案: 不推薦


如果你總是假設dates和cases總是相同的長度,那么你可以這樣做:


{this.state.dates.map((el, index) => (

  <tr>

    <td>{this.state.dates[index]}</td>

    <td>{this.state.cases[index]}</td>

  </tr>

))}

該方法利用了函數index的參數map。然后您可以訪問指定索引處的數組。


推薦解決方案:


通常的做法是按記錄對數據進行分組。


使用您的示例,使用如下結構:


state  = {

  records: [

    { date: '2000', caseId: '1' },

    { date: '2001', caseId: '2' },

    { date: '2002', caseId: '3' }

  ],

}

然后像這樣實現它:


{this.state.records.map(({ date, caseId }) => (

  <tr>

    <td>{date}</td>

    <td>{caseId}</td>

  </tr>

))}

我使用caseIdnot 來代替,case因為它case是 JavaScript 中語句的保留字switch。


查看完整回答
反對 回復 2023-12-11
?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

您可以使用index映射函數中的參數并訪問案例數組


<tbody>

  {this.state.dates.map((el, index) => (

    <tr>

      <td>{el}</td>

      <td>{this.state.cases[index]}</td>

    </tr>

  ))}{" "}

</tbody>;


查看完整回答
反對 回復 2023-12-11
  • 2 回答
  • 0 關注
  • 170 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號