2016-12-05 135 views
1

我試圖渲染使用動態表數據結構如下反應:動態表陣營

{ 
    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>) 

感謝

回答

2

你的表的結構是這裏的主要問題。

爲了有更好的解決方案,請嘗試重構您的表格數據。

如果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); 
 
    } 
 
    }

+0

謝謝! N^2是一大改進:) –