【发布时间】:2020-01-29 08:46:27
【问题描述】:
我一直在尝试使用 d3 和 reactjs 创建饼图,但不确定将我从 api 获取的数据动态传递到饼图的位置。 d3js 中的饼图是否接受对象作为数据,因为这就是我从 api 接收数据的方式,即标签和值
我的代码看起来像这样
performAnalysis = async () => {
const { enteredText } = this.state;
const body = { snippetdesc: enteredText };
const stringifiedBody = JSON.stringify(body);
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: stringifiedBody
};
const url = "/api/analyse";
try {
const response = await fetch(url, options);
const result = await response.json();
const {
...sentimentAnalysis
} = result.scores;
const sentimentAnalysisArray = Object.entries(sentimentAnalysis).reduce(
(carry, [emotion, value]) => [
...carry,
{ emotion, value: parseInt(parseFloat(value) * 100) }
],
[]
);
this.setState({
analysis: {
...this.state.analysis,
sentiments: sentimentAnalysisArray
}
});
console.log("the data"+"\n"+JSON.stringify(this.state.analysis.sentiments)); //need to send this sentiments object to the pie-chart
} catch (error) {
console.error(error);
}
};
上面的控制台日志给出如下输出:
[{"emotion":"Neutral","value":52},{"emotion":"Positive","value":27}, {"emotion":"Negative","value":19}]
我需要在饼图中将上述“情感”和“价值”显示为标签和值。如何提取这些数据并将其发送到 hooks 组件?
这是在渲染中将数据发送到 PieHooks 组件的样子:
return (
<div className="App">
<div>
<button onClick={performAnalysis}>Analyse</button>
</div>
<div>
<span className="label">Pie Chart</span>
<PieHooks
data={data}
width={200}
height={200}
innerRadius={60}
outerRadius={100}
/>
</div>
</div>
)
【问题讨论】:
-
饼图你用的是哪个npm???
-
@PrakashKarena 我刚刚做了
npm install d3,所以我认为它必须安装最新版本的 d3 -
我找到了一个例子。它显示了如何添加带有您的值的自定义标签看看swizec.com/blog/how-to-make-a-piechart-using-react-and-d3/…
-
我的问题是我不知道如何将从 api 调用中获得的数据发送到 pieHooks 组件。即使没有标签也可以。我只想要价值观。如何将值转换为数组并将其发送到饼图组件?上面的教程没有显示它