JavaScript:基于数据库列表创建Shape.Rect对象并批量加载的问题
解决方法
问题根源在于你每次循环都调用stencil.load,传入单个Shape.Rect对象——这个函数不支持增量添加,每次调用都会覆盖之前的内容,所以最终只有最后一个项被注册。
正确的做法是先把所有需要的Shape对象收集到一个数组里,循环结束后一次性调用stencil.load:
... // 先创建一个空数组存放所有Shape对象 const shapes = []; this.items.forEach((item) => { const rect = new Shape.Rect({ shape: 'rect', label: item.component_name, id: item.component_id, x: 5, y: 50, width: 100, height: 25, }); // 将每个对象加入数组 shapes.push(rect); }); // 循环结束后一次性加载整个数组 stencil.load(shapes, 'group1'); ...
或者用map更简洁:
... const shapes = this.items.map(item => new Shape.Rect({ shape: 'rect', label: item.component_name, id: item.component_id, x: 5, y: 50, width: 100, height: 25, })); stencil.load(shapes, 'group1'); ...
内容的提问来源于stack exchange,提问作者jeffmayn
相关产品推荐
相关产品推荐

