试图从 https://bl.ocks.org/mbostock/4657115 使用 React.js 获取一个示例。
我收到错误:Attempted import error: 'queue' is not exported from 'd3' (imported as 'd3').
但是,安装d3-queue
后,我在组件中尝试了以下导入:
import * as d3queue from 'd3-queue';
import {queue} from 'd3-queue';
但两者都不能解决错误。
我错过了什么? 还是我错过了弃用?
我的代码:
import React from 'react';
import * as d3 from 'd3';
import * as d3queue from 'd3-queue';
import * as topojson from 'topojson';
export default class CongressionalDistricts extends React.Component {
state = {
usData: null,
usCongress: null
}
componentWillMount() {
d3.queue()
.defer(d3.json, "us.json")
.defer(d3.json, "us_congress_113.json")
.await((error, usData, usCongress) => {
this.setState({
usData,
usCongress
});
})
}
componentDidUpdate() {
const svg = d3.select(this.refs.anchor),
{width, height} = this.props;
const projection = d3.geoAlbers()
.scale(1280)
.translate([width / 2, height / 2]);
const path = d3.geoPath(projection);
const us= this.state.usData,
congress = this.state.usCongress
svg.append("defs").append("path")
.attr("id", "land")
.datum(topojson.feature(us, us.objects.land))
.attr("d", path);
svg.append("clipPath")
.attr("id", "clip-land")
.append("use")
.attr("xlink:href", "#land");
svg.append("g")
.attr("class", "districts")
.attr("clip-path", "url(#clip-land)")
.selectAll("path")
.data(topojson.feature(congress, congress.objects.districts).features)
.enter().append("path")
.attr("d", path)
.append("title")
.text(function(d) { return d.id; });
svg.append("path")
.attr("class", "district-boundaries")
.datum(topojson.mesh(congress, congress.objects.districts, function(a, b) { return a !== b && (a.id / 1000 | 0) === (b.id / 1000 | 0); }))
.attr("d", path);
svg.append("path")
.attr("class", "state-boundaries")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("d", path);
}
render() {
const { usData, usCongress } = this.state;
if (!usData || !usCongress) {
return null;
}
return <g ref="anchor" />
}
}
如果您使用的是 D3.v5,则在尝试使用 d3.queue()
时会遇到相同的错误,因为它已被 Promise.all()
替换。
下面是如何使用它的示例:
Promise.all([
d3.csv('data1.csv'),
d3.csv('data2.csv')
]).then( ([data1, data2]) => {
// do stuff
console.log(data1, data2);
}).catch(err => console.log('Error loading or parsing data.'))
您可以通过在终端上运行以下命令来了解您正在使用的 D3 版本:npm list d3
。
您是否尝试使用require
而不是导入?
const { queue } = require("d3-queue");