useEffect不打印div元素的反应钩子



我有这个Chart组件。useEffect作为componentDidMount()工作,所以它应该首先渲染DOM,然后应该调用fetchChartData。但我在这里面临的问题是,我首先在console.log("111111111", document.getElementById("data-consumed"))中得到null,之后我得到DOM元素,结果我从Highcharts

中得到错误
Uncaught (in promise) Error: Highcharts error #13

所以我需要知道为什么这会发生,因为useEffect作为componentDidMount工作,应该首先渲染DOM。

const Chart2 = (props) => {
const fetchChartData = async () => {
const { fetchChartData } = props;
const startDate = moment().startOf("year").toISOString();
const endDate = moment().endOf("year").toISOString();
const data = await fetchChartData({ startDate, endDate, userId: "XXXXXXX" });
console.log("111111111", document.getElementById("data-consumed"))
Highcharts.chart("data-consumed", {
chart: {
type: "column",
},
title: {
text: null,
},
subtitle: {
text: "Source: WorldClimate.com",
},
xAxis: {
categories: data.map(({ _id }) => _id),
crosshair: true,
},
yAxis: {
min: 0,
title: {
text: "Rainfall (mm)",
},
},
plotOptions: {
column: {
pointPadding: -0.1,
borderWidth: 0,
color: "#5036D6",
},
},
series: [
{
name: null,
data: data.map(({ processingStorage }) => processingStorage),
},
],
});
};
useEffect(() => {
fetchChartData();
}, []);
return (
<div className="chart-container cursor-pointer">
<div className="chart-block">
<h4>Data Consumed</h4>
<div id="data-consumed" className="graph-block" />
</div>
</div>
);
};
export default Chart2;

尝试使用setTimeout函数。在setTimeout

内部调用fetchChartData函数
useEffect(() => {
setTimeout(()=> {
fetchChartData();
}, 2000)
}, []);

相关内容

  • 没有找到相关文章

最新更新