2016-12-05 11 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

あなたのテーブルの構造は、ここでは主要な関心事です。

もっと良い解決策を得るためには、テーブルデータを再構成してみてください。

memorytimeと比較して問題でない場合は、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は大きな改善点です:) –

関連する問題