首页 > 解决方案 > 尝试使用 Promise 将 d3 v3 地图迁移到 d3 v5 地图

问题描述

我正在尝试将使用 d3.js 第 3 版创建的地图迁移到第 5 版。但是,第 5 版使用承诺,我不确定如何更改 d3.json 方法以使用承诺。如何更改现有的 v3 代码以使用 v5 承诺?谢谢你。

我正在使用的原始 d3.json 方法:

d3.json("ne_50m_admin_0_countries_simplified.json", function(json) {
                
                //Bind data and create one path per GeoJSON feature
                svg.selectAll("path")
                   .data(json.features)
                   .enter()
                   .append("path")
                   .attr("d", path)
                   .attr("stroke", "rgba(8, 81, 156, 0.2)")
                   .attr("fill", "rgba(8, 81, 156, 0.6)");
        
            });

尝试更改它以利用调用 d3.json 的新承诺方式。不生成地图。

d3.json("ne_50m_admin_0_countries_simplified.json").then(data => {
                svg.selectAll("path")
                   .data(json.features)
                   .enter()
                   .append("path")
                   .attr("d", path)
                   .attr("stroke", "rgba(8, 81, 156, 0.2)")
                   .attr("fill", "rgba(8, 81, 156, 0.6)");
});

标签: javascriptd3.js

解决方案


您似乎在回调函数中使用“数据”作为变量名而不是“json”。

尝试

d3.json("ne_50m_admin_0_countries_simplified.json").then(json => {
                svg.selectAll("path")
                   .data(json.features)
                   .enter()
                   .append("path")
                   .attr("d", path)
                   .attr("stroke", "rgba(8, 81, 156, 0.2)")
                   .attr("fill", "rgba(8, 81, 156, 0.6)");
});

推荐阅读