[英]Cannot get data formatted correctly for apexcharts
我從 API 接收這樣的數據
{
"Bob Knight": 30774.72000002,
"Samuel Herman": 10310.61000004,
"Lucie Perry": 26308.41,
"Andreas Smith": 8960.189999999999,
"Frederic Smith": 2029.5000000599998,
}
我試圖在我的 React 應用程序中使用頂點圖表在條形圖中顯示它,但是我似乎無法以正確的方式格式化數據以使頂點顯示任何內容。 我試過在 javascript 中這樣格式化:
{
{x: "Bob Knight", y:"30774.720002"},
...
}
這似乎是文檔建議的內容,但它沒有呈現任何內容。 以下是我的組件的有用部分
constructor(props) {
super(props);
this.state = {
options: {
chart: {
id: "basic-bar"
},
xaxis: {
type: 'category'
}
},
values: []
}
}
componentDidUpdate(prevProps) {
if (!equal(this.props.selectedDate, prevProps.selectedDate))
{
var m = moment(this.props.selectedDate).format("M");
var y = moment(this.props.selectedDate).format("YYYY");
axios.get('http://localhost:8080/opportunity/owner/' + y + '/' + m)
.then(res => {
values = res.data;
this.setState({
values
})
})
.catch(console.log)
}
}
render(
<Chart series = {this.state.values} type ='bar' options ={this.state.options}/>
const obj = { "Bob Knight": 30774.72000002, "Samuel Herman": 10310.61000004, "Lucie Perry": 26308.41, "Andreas Smith": 8960.189999999999, "Frederic Smith": 2029.5000000599998, } const arr = Object.entries(obj).map(x => ({ 'x': x[0], 'y': x[1] })) console.log(arr)
結帳這個codesandbox ,我實現一個簡單的條形圖, data
是y軸值和categories
在xaxis
是x軸標簽。 所以從對象中你可以像這樣將它們分開
const obj = {
"Bob Knight": 30774.72000002,
"Samuel Herman": 10310.61000004,
"Lucie Perry": 26308.41,
"Andreas Smith": 8960.189999999999,
"Frederic Smith": 2029.5000000599998
};
let categories = Object.keys(obj);
let data = Object.keys(obj).map(k => obj[k]);
這樣做之后,像這樣在狀態中設置類別和數據
this.setState({
values: [...this.state.series, { data }],
options: { ...this.state.options, xaxis: { categories } }
});
您必須將類別添加到options
對象中的xaxis
並將數據添加到values
數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.