Cytoscape:在 setTimeout 中添加元素不会被渲染

Cytoscape : Add element in setTimeout doesn't get rendered

在下面的代码中,我向 setTimout 中的图形添加了一个节点,但它没有呈现。当我将代码移出 setTimeout 时,它被绘制出来。任何原因 ?

var cytoscape = require('cytoscape');

var cy = cytoscape({
    container: document.getElementById('container'),
    layout: {
        name: 'circle'
    }
});

cy.add({
        group: "nodes",
        data: {
            id: 'id1'
        }
    }
); // this adding is drawn
console.log(cy.nodes()); // this shows that the node with id:id1 is added 

setTimeout(function() {
    cy.add({
            group: "nodes",
            data: {
                id: 'id2'
            }
        }
    ); // this one doesn't get drawn
    console.log(cy.nodes()); // BUT, this shows that the node with id:id2 is added 
}, 500);

您还没有定义位置,所以节点无法渲染。显式定义节点位置或显式调用布局。

说明:假设这是在页面的初始化上,您已经创建了一个竞争条件:图表在 DOMContentLoaded 之前无法呈现。因此,布局会延迟到该事件之后。您已经创建了在布局之前添加 id1 并在布局之后添加 id2 的情况。所以,id1有位置,可以渲染,而id2没有位置,不能渲染。

在2.4.8中,节点将有a default position of (0, 0)以更容易避免这样的错误。