项目场景:
提示:这里简述项目相关背景:
需要实现各个级别的关系图,找了一圈也没有什么好的方法,突然看到@antv/G6,所以使用G6引擎,然后就遇到错误了。(关于g6引擎的文章太少了!)
问题描述
提示:这里描述项目中遇到的问题:
渲染数据的时候会报错,TypeError: Cannot read properties of undefined (reading 'set')
部分数据代码:
//处理数据函数
handlePosition(data) {
let arr = {
id: '0',
label: '中国',
children: []
}
let result = data.reduce((acc, cur) => {
if (!acc[obj.yName]) {
acc[obj.yName] = { id: cur.id, label: obj.yName, children: [] }
}
acc[obj.yName].children.push(obj)
return acc
}, {})
for (const key in result) {
arr.children.push(result[key])
}
arr.children.forEach((item,index)=>{
item.children.map((el,i)=>{
let obj = {
id :el.guId,
label :el.zdName,
children : []
}
item.children[i] = obj
})
})
return arr
},
//-------------------------------------请求数据-------------
postJson(this.url.getRoadNetPoint, {
userId: this.getUserId,
caseId: this.getCaseId
}).then(res => {
this.arrayLists = this.handlePosition(res.data)
})
//--------------------------------------g6部分代码----------------------------
const data = this.arrayLists//把处理的数据赋值给data
let container = document.getElementById('mountNode')
let width = container.scrollWidth
const height = container.scrollHeight || 600
const graph = new G6.TreeGraph({
container: container, // String | HTMLElement,必须,在 Step 1 中创建的容器 id 或容器本身
width: width, // Number,必须,图的宽度
height: height, // Number,必须,图的高度
//.....其他代码
})
graph.data(data); // 读取 Step 2 中的数据源到图上
graph.render(); // 渲染图
graph.fitView() // 支持伸缩
原因分析:
上面的代码是cur.id
不是唯一的,所以导致出错了。data
中的id
不能重复,要不渲染的时候它懵逼了,最后搞得我懵逼了,浪费了两个小时,好在最后搞出来了。
解决方案:
要确保data
中的每一层数据的id
都要确保唯一性