未找到Amchart HTML容器(React)



EDIT 1(initial(:似乎setState((回调没有按我预期的方式工作。例如:

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

将注销"true",而我希望它注销false。

编辑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容器未找到错误。

除了使用css之外,最好的处理方法是什么?

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

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

分辨率是将<script>部分放置在<div id="chartdiv"></div>之后

在这里写这篇文章是为了帮助任何可能自己遇到这种情况的人。

下面的代码是您的逻辑的示例片段,在回调函数上,您将能够获得元素。

请检查解决方案,让我知道你是否面临任何问题或它解决了它。

注意-示例代码,但我希望其逻辑相同。打开控制台并执行代码。

import React, { Component } from 'react';
import './App.css';
class App extends Component {
state = {
countrySelected: null
}
onCountryChange = (e) => {
this.setState({
countrySelected: e.target.value
}, () => {
// getting the id
let id = document.getElementById("barChartDiv");
console.log("id =>", id)
})
}

render() {
return (
<div>
<select onChange={this.onCountryChange}>
<option value="India">India</option>
<option value="USA">USA</option>
</select>
{
this.state.countrySelected === "India" ?
<div id="barChartDiv" style={{ width: "100%", height: "500px" }} />
:
null
}
</div>
);
}
}
export default App;

最新更新