将多个数组渲染到表中的函数创建空td标记

时间:2018-05-11 23:52:42

标签: reactjs ecmascript-6

我组合数组以在表格中输出数据。 到目前为止合并成功..但在那之后我认为有些事情出了问题。解决方案必须非常简单,但是在这一点上我无法弄明白......似乎在map函数的每个循环之后都会创建空的td标签来推动行。

TESTDATA:

export const arr1 = [{
  "tre": 1,
  "tro": "Nikkie"
}, {
  "tre": 2,
  "tro": "Donia"
}, {
  "tre": 3,
  "tro": "Lavena"
}];

export const arr2 = [{
  "bla": 1,
  "blo": "Carola"
}, {
  "bla": 2,
  "blo": "Rosa"
}, {
  "bla": 3,
  "blo": "Geneva"
}];

export const arr3 = [{
  "bra": 1,
  "bru": "Currie"
}, {
  "bra": 2,
  "bru": "Aura"
}, {
  "bra": 3,
  "bru": "Irwinn"
}];

功能:

tableData() {
    const combined = [...arr1, ...arr2, ...arr3];

    var data = combined.map((i, k) => {
      return (
        <tr key={k}>
          <td>{i.tre}</td>
          <td>{i.tro}</td>
          <td>{i.bla}</td>
          <td>{i.blo}</td>
          <td>{i.bra}</td>
          <td>{i.bru}</td>
        </tr>
      )
    })
    return data
  }

  render() {
    return (
      <div className="table-responsive">
        <table className="table table-sm table-hover">
          <thead>
            <tr>
              <th>rank</th>
              <th>name</th>
              <th>rank</th>
              <th>name</th>
              <th>rank</th>
              <th>name</th>
            </tr>
          </thead>
          <tbody>
            {this.tableData}
          </tbody>
        </table>
      </div>
      )
     }

看起来像:

enter image description here

使用以下方式更新:

      <td>{i.tre || 'test TRE'}</td>
      <td>{i.tro || 'test TRO'}</td>
      <td>{i.bla || 'test BLA'}</td>
      <td>{i.blo || 'test BLO'}</td>
      <td>{i.bra || 'test BRA'}</td>
      <td>{i.bru || 'test BRU'}</td>

enter image description here

1 个答案:

答案 0 :(得分:0)

td代码可能是因为来自combined的对象没有您尝试访问的所有属性,而map正在返回undefined他们。尝试以下操作,也许您将能够解决这个问题。如果您在表格中看到Test ...,则会知道缺少哪个属性。

希望有所帮助

tableData() {
    const combined = [...arr1, ...arr2, ...arr3];

    var data = combined.map((i, k) => {
      return (
        <tr key={k}>
          <td>{i.tre || "Test TRE" }</td>
          <td>{i.tro || "Test TRO" }</td>
          <td>{i.bla || "Test BLA" }</td>
          <td>{i.blo || "Test BLO" }</td>
          <td>{i.bra || "Test BRA" }</td>
          <td>{i.bru || "Test BRU" }</td>
        </tr>
      )
    })
    return data
  }

  render() {
    return (
      <div className="table-responsive">
        <table className="table table-sm table-hover">
          <thead>
            <tr>
              <th>rank</th>
              <th>name</th>
              <th>rank</th>
              <th>name</th>
              <th>rank</th>
              <th>name</th>
            </tr>
          </thead>
          <tbody>
            {this.tableData}
          </tbody>
        </table>
      </div>
      )
     }

PS:如果您为combined提供更多数据,那就太好了。

相关问题