首页 > 解决方案 > 找不到 Amchart HTML 容器 (React)

问题描述

编辑 1(初始): setState() 回调似乎没有按我期望的方式工作。例如:

this.state = {table: true}
this.setState({table: false}, ()=> console.log(this.state.table)); 

当我希望它注销错误时,将注销“真”。

编辑2:我认为我处理下拉请求的方式有问题,这可能导致我的大部分问题。所以我将把它标记为已解决,因为 Dileep 的解决方案应该有效。我将在几个小时内更新我的结果。

编辑 3(最终):我使用的是 switch() 语句,它以某种方式触发了多个案例并重置了我的状态。

我想我明白问题是什么,但是,我不完全确定如何解决它。

我想有条件地渲染一个元素,然后才能被 Amchart 的 create("elementID", chartType) 函数访问。我希望通过调用以下函数在下拉列表中呈现:

loadBarChart() {
this.setState({ piechart: false, table: false, barchart: true });
var chart = am4core.create("barChartDiv", am4charts.XYChart);
chart.data = this.state.data;

let categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "schoolname";
categoryAxis.title.text = "Schools";

let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.title.text = "Number of Students";
}

barChartDiv 显示如下:

 {this.state.barchart && (
      <section>
        <h1 style={{ textAlign: "center" }}>School Data</h1>
        <div id="barChartDiv" style={{ width: "100%", height: "500px" }} />
      </section>
 )}

当我选择下拉时,我被告知 barchart 为 false,然后在出现以下错误后为 true:

Instance.js:128 Uncaught Error: html container not found

因为 setState() 通常不会立即更新。我已经尝试通过在 setState() 回调函数中包含 loadBarChart() 代码来解决这个问题,但我得到了与以前相同的错误。所以我几乎可以肯定正在发生的是 am4core.create() 在呈现该元素之前正在寻找一个 id 为“barChartDiv”的元素,所以我得到一个 html container not found 错误。

除了使用 css 之外,处理这个问题的最佳方法是什么?

标签: javascripthtmlreactjschartsconditional-rendering

解决方案


我在纯 HTML/JS 中遇到了这个错误。

在出错时,我<script>在我之前添加了该部分<div id="chartdiv"></div>

决议是将<script>部分放在<div id="chartdiv"></div>

在这里写这篇文章是为了帮助任何可能自己遇到这个问题的人。


推荐阅读