貼代碼:
// Grid-》Tree 結構組裝。
var tree = [];
this.setTreeData(table, tree, "");
//組裝樹形
setTreeData = (source, list, pid) => {
if (typeof (source) == "undefined") return;
source.forEach((father) => {
if (father.PID == pid) {
list.push(father);
if (!father.IsLowest) {
if (typeof (father.children) == "undefined") {
father.children = [];
}
father.children = this.setTreeData(source, father.children, father.ContractListDtlID);
}
}
//Tree -> 數組機構
//樹形數據轉換成grid,調用者自己決定children 屬性刪除與否 2019-
var list= [];
this.setGridDataFromTree(list, tree, "");
setGridDataFromTree= function(list,dataSource){
if (!(Array.isArray(dataSource) && dataSource.length >0)) return ;
dataSource.forEach((father) => {
// debugger;
list.push(father);
if (typeof (father.children) == "undefined") {
} else {
this.setGridDataFromTree(list, father.children);
}
});
// return;
}
})
return list;
}
如上代碼在開發React項目, 用到內容。
需要注意的是, Gird 與Tree 結構轉換是一個引用賦值。 也就是說改gird 或者treeData之后 值會影響變。
不需要的話,深拷貝之后再轉。
淺拷貝的好處就是利用引用特性, 改treeData 值界面保存后去gridData 是可以的, 減少了TreeData -》 GridData 操作。
當然控件本身需要額外增加這種判斷,來做顯示界面刷新。
shouldComponentUpdate(newProps, newState) {
if (newProps.tableData !== this.props.tableData
|| JSON.stringify(newProps.tableData) !== JSON.stringify(this.props.tableData)) {
this.loadData(newProps);
}
// debugger;
return true;
}