我正在尝试基于此 resource 创建一个 d3 饼图.
但是,我收到以下错误:
Uncaught Type Error - Cannot read property 'pie' of undefined
我的代码:
class PieChart extends React.Component {
constructor() {
super();
// - This is where the error is occuring!
this.pie = d3.layout.pie().value((d) => d.value);
this.colors = d3.scale.category10();
}
arcGenerator(d, i) {
return (
<LabeledArc key = {`arc-${i}`}
data = {d}
innerRadius = {this.props.innerRadius}
outerRadius = { this.props.outerRadius }
color = {this.colors(i)} />
);
}
render() {
console.log('Render Method Fires');
let pie = this.pie(this.props.data),
translate = `translate(${this.props.x}, ${this.props.y})`;
return (
<g transform={translate}>
{pie.map((d, i) => this.arcGenerator(d, i))}
</g>
);
}
}
我认为我已正确设置所有内容。我正在使用 react-rails gem 以及 d3-rails。我必须下载 d3.js 并将其直接放在我的 js 文件夹中以摆脱“找不到 d3”的问题。
谁能给我指出正确的方向,也许您有更好的资源来在 rails 中添加 d3 + react 功能?
最佳答案
就像之前在许多类似问题中看到的那样,归因于 D3 v4 的新模块化,这使得有必要 flatten namespaces :
However, there is one unavoidable consequence of adopting ES6 modules: every symbol in D3 4.0 now shares a flat namespace rather than the nested one of D3 3.x.
对于您的代码,这意味着某些引用无效,因为它们引用的属性在 v4 中不再可用。您包含的代码段包含两个这样的案例:
Shapes
- d3.layout.pie ↦ d3.pie
在你的代码的下一行
Scales
- d3.scale.category10 ↦ d3.schemeCategory10
关于javascript - D3 饼图 : Uncaught Type Error - Cannot read property 'pie' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40358268/