我正在尝试使用对以下数据结构的反应来呈现动态表:

{
  numRows: 2,
  numCols: 3,
  cells: [
    {
      id: 1,
      pos: {
        row: 1,
        col: 1
      },
      content: 'This is the content 1'
    },
    {
      id: 2,
      pos: {
        row: 1,
        col: 2
      },
      content: 'This is the content 2'
    },
    {
      id: 3,
      pos: {
        row: 1,
        col: 3
      },
      content: 'This is the content 2.5'
    },
    {
      id: 4,
      pos: {
        row: 2,
        col: 1
      },
      content: 'This is the content 3'
    },
    {
      id: 5,
      pos: {
        row: 2,
        col: 3
      },
      content: 'This is the content 4'
    }
  ]
}


我认为此数据结构最适合我的应用程序,因为用户可以无序编辑单元格,但是如果有更好的方法,请告诉我。

我有以下逻辑将数据呈现到表中,但是它包含许多循环,所以我想知道是否存在更好/更有效的呈现此数据结构的方法?

let rows = []

for (let row = 1; row <= numRows; row++) {
  let children = []

  for (let col = 1; col <= numCols; col++) {
    let hasCell = false
    cells.forEach((cell) => {
      if (cell.pos.row === row && cell.pos.col === col) {
        hasCell = true
        children.push(<Cell>{cell.content}</Cell>)
      }
    })

    if (!hasCell) {
      children.push(<Cell />)
    }
  }

  rows.push(<Row>{children}</Row>)


谢谢

最佳答案

表的结构是这里的主要问题。

为了获得更好的解决方案,请尝试重组表数据。

如果与memory相比,time不是一个问题,则可以设法将N^3迭代减少为N^2迭代解决方案。



var tableData = {
  numRows: 2,
  numCols: 3,
  cells: [
    {
      id: 1,
      pos: {
        row: 1,
        col: 1
      },
      content: 'This is the content 1'
    },
    {
      id: 2,
      pos: {
        row: 1,
        col: 2
      },
      content: 'This is the content 2'
    },
    {
      id: 3,
      pos: {
        row: 1,
        col: 3
      },
      content: 'This is the content 2.5'
    },
    {
      id: 4,
      pos: {
        row: 2,
        col: 1
      },
      content: 'This is the content 3'
    },
    {
      id: 5,
      pos: {
        row: 2,
        col: 3
      },
      content: 'This is the content 4'
    }
  ]
};

function createEmptyTable(rows, cols){
  var arr = [];
  for(var i = 0; i < rows; i++){
    arr.push(new Array(cols));
  }
  return arr;
}

var rows = tableData.numRows;
var cols = tableData.numCols;
var table  = createEmptyTable(rows, cols); //crate empty table 2D
tableData.cells.forEach(function(cell, i){
  table[cell.pos.row-1][cell.pos.col-1] = cell //cell data into table cell
});

console.log(table); //table structure

for(var i = 0; i < rows; i++)
  for(var j = 0; j < cols; j++){
    var cell = table[i][j];
    if(cell){
      //your render method here
      console.log(cell.content);
    }
  }

09-17 05:01