我正在使用https://www.amcharts.com/docs/v3/在我的页面上创建图表。 数据来自api。
在我将数据生成到amchart之后,它给了我错误消息Uncaught TypeError: Cannot read property 'write' of undefined
以及用于生成数据的代码:
从api获取数据
generateChart() {
const { priceItem } = this.state
let dataProvider = []
priceItem.forEach(item => {
dataProvider.push({
"date": moment(new Date(item.date)).format('DD-MM-YYYY'),
"value": item.amount
})
})
var result = simpleConfig(dataProvider)
this.setState({ config: result })
}
然后我在另一个文件中创建配置:
export const simpleConfig = (dataProvider) => {
dataProvider.map(data => {
console.log(data)
let config = {
"type": "stock",
"theme": "light",
"dataDateFormat": "DD-MM-YYYY",
"dataSets": [{
"title": "first data set",
"fieldMappings": [{
"fromField": "value",
"toField": "value"
}, {
"fromField": "volume",
"toField": "volume"
}],
"dataProvider": data,
"categoryField": "date"
}],
"panels": [{
"showCategoryAxis": false,
"title": "value",
"percentHeight": 70,
"stockGraphs": [{
"id": "g1",
"valueField": "value",
"comparable": false,
"compareField": "value",
"balloonText": "[[title]]:<b>[[value]]</b>",
"compareGraphBalloonText": "[[title]]:<b>[[value]]</b>"
}],
"stockLegend": {
"periodValueTextComparing": "[[percents.value.close]]%",
"periodValueTextRegular": "[[value.close]]"
}
}],
"chartCursorSettings": {
"valueBalloonsEnabled": true,
"fullWidth": true,
"cursorAlpha": 0.1,
"valueLineBalloonEnabled": true,
"valueLineEnabled": true,
"valueLineAlpha": 0.5
},
"export": {
"enabled": false
},
"responsive": {
"enabled": true
}
}
return config;
})
}
然后显示图表:
<AmCharts.React
style={{
width: "100%",
height: "500px"
}}
options={config}
/>
我做错了什么吗?
答案 0 :(得分:0)
在配置方法中映射dataProvider不正确。您的代码正在执行的操作是在dataProvider
属性中生成带有单个数据项的配置对象数组,而不是将整个数组分配给dataProvider
。只需将dataProvider变量分配给您的配置即可,而不是循环遍历它:
export const simpleConfig = (dataProvider) => {
let config = {
"type": "stock",
"theme": "light",
"dataDateFormat": "DD-MM-YYYY",
"dataSets": [{
"title": "first data set",
"fieldMappings": [{
"fromField": "value",
"toField": "value"
}, {
"fromField": "volume",
"toField": "volume"
}],
"dataProvider": dataProvider,
"categoryField": "date"
}],
"panels": [{
"showCategoryAxis": false,
"title": "value",
"percentHeight": 70,
"stockGraphs": [{
"id": "g1",
"valueField": "value",
"comparable": false,
"compareField": "value",
"balloonText": "[[title]]:<b>[[value]]</b>",
"compareGraphBalloonText": "[[title]]:<b>[[value]]</b>"
}],
"stockLegend": {
"periodValueTextComparing": "[[percents.value.close]]%",
"periodValueTextRegular": "[[value.close]]"
}
}],
"chartCursorSettings": {
"valueBalloonsEnabled": true,
"fullWidth": true,
"cursorAlpha": 0.1,
"valueLineBalloonEnabled": true,
"valueLineEnabled": true,
"valueLineAlpha": 0.5
},
"export": {
"enabled": false
},
"responsive": {
"enabled": true
}
}
return config;
}