reactjs - 如何使用 ReactJS 和 AmChart 将数据传递到状态
问题描述
我创建了一个 Web 应用程序,它使用 amChart 显示报告并遵循 ReactJS amChart 实现,现在我试图将 firebase 查询结果传递到 ReactJS 状态,但无法说明为什么我无法显示状态数据值。
我的想法是将所有费用数据和利润数据相加,然后设置每个数据,然后将其传递给 amChart chart.data 数组
到目前为止我的代码。
componentDidMount () {
am4core.useTheme(am4themes_animated);
let chart = am4core.create("chartdiv", am4charts.XYChart);
let expense = 0;
let profit = 0;
const citiesRef = db.collection('transactions');
// Create a query against the collection
const queryRef = citiesRef.where('category', '==', 'Expense').get();
const queryProf = citiesRef.where('category', '==', 'Profit').get();
queryRef.then(ref=> {
ref.docs.forEach(doc => {
expense += parseInt(doc.data().amount)
})
return this.setState( { totalExpense: expense } )
})
queryProf.then(ref=> {
ref.docs.forEach(doc => {
profit += parseInt(doc.data().amount)
})
return this.setState( { totalProfit: profit } )
})
chart.data = [
{
"year": "2003",
"expense": this.state.totalExpense,
"profit": this.state.totalProfit,
}
];
// Rest of the chart code..
}
解决方案
由于setState
是异步的,因此您永远不会以这种方式获得结果。
你需要描述你的componentDidMount
方法async componentDidMount
,然后await
才能完成承诺
await queryRef.then(ref=> {
和
await queryProf.then(ref=> {
推荐阅读
- python - AttributeError:“DataFrame”对象没有属性“_example”
- javascript - VB.net 或 Javascript 来检查 LAN 中的连接
- html - Html 悬停子菜单
- php - 在没有 user_likes 权限的情况下检查用户是否喜欢页面
- ruby-on-rails - Rails 更新控制台中的嵌套属性
- ios - UITableViewCell 与下拉 UITableView
- angularjs - 在 AngularJS 中发生 ng-if、ng-show 等之后,我该如何做一些动作?
- spring - IgniteSpringBean 和 Ignite SpringTransactionManager 在 2.4 中不再一起工作
- javascript - 错误:找不到模块“data-service.js”
- activejdbc - ActiveJDBC 有flush吗?