【发布时间】:2017-12-14 08:05:54
【问题描述】:
我正在尝试将 D3 与 react 集成,请在下面找到代码 sn-p。
在代码中,我试图在 D3 中实现一个简单的行并做出反应。但我最终得到Error: <path> attribute d: Expected number, "MNaN,191.94630872…
stackoverflow 上有类似的问题,但它们也无济于事。
attribute d: Expected number, "MNaN,NaNLNaN,NaNL…". react with d3
"Error: <path> attribute d: Expected number, "MNaN,NaNLNaN,NaNL…". " Error with D3
我尝试做的几件事。
A:最初我认为日期解析有问题,所以我将我的day 密钥更改为number 并删除了日期解析,最终我遇到了同样的错误。
B:A 假设 x 和 y 的域声明存在问题。我删除了extend并给出了一个离散值,仍然面临同样的错误。
import React, { Component } from 'react';
import * as d3 from "d3";
class LineChart extends Component {
constructor(props) {
super(props);
this.state = {selected: props.width || null};
}
componentWillMount() {
}
componentWillReceiveProps(nextProps) {
}
render() {
let data=[
{day:'02-11-2016',count:180},
{day:'02-12-2016',count:250},
{day:'02-13-2016',count:150},
{day:'02-14-2016',count:496},
{day:'02-15-2016',count:140},
{day:'02-16-2016',count:380},
{day:'02-17-2016',count:100},
{day:'02-18-2016',count:150}
];
let margin = {top: 5, right: 50, bottom: 20, left: 50},
w = this.state.width - (margin.left + margin.right),
h = this.props.height - (margin.top + margin.bottom);
let parseDate = d3.timeParse("%m-%d-%Y");
data.forEach(function (d) {
d.date = parseDate(d.day);
});
let x = d3.scaleTime()
.domain(d3.extent(data, function (d) {
return d.date;
}))
.range([0, w]);
let y = d3.scaleLinear()
.domain([ 0 , d3.max( data, function(d) {
return d.count + 100;
})])
.range([ h, 0 ]);
let line = d3.line()
.x(function (d) {
return x(d.date);
})
.y(function (d) {
return y(d.count);
}).curve(d3.curveCardinal);
let transform = 'translate(' + margin.left + ',' + margin.top + ')';
return (
<div>
<p>LineChart</p>
<svg id={this.props.chartId} width={this.state.width} height={this.props.height}>
<g transform={transform}>
<path className="line shadow" d={line(data)} strokeLinecap="round"/>
</g>
</svg>
</div>
)
}
}
LineChart.defaultProps = {
width: 800,
height: 300,
chartId: 'v1_chart'
}
export default LineChart;
【问题讨论】:
-
您正在使用
this.state.width来初始化w。这将是undefined导致w是NaN,因此出现错误。从这个JSFiddle 可以看出,其余代码运行良好。使用this.props.width获取宽度,就像获取高度一样。
标签: javascript reactjs d3.js