【发布时间】:2020-08-03 13:34:37
【问题描述】:
我有一个组件,我在其中使用钩子useEffect 从 API 检索数据。我想使用 AMCharts 在图表中显示数据。我的问题是我需要使用钩子useLayoutEffect来创建图表,并且图表基于使用useEffect检索到的数据...当我的图表被渲染时,我还没有数据和我的图表是空的。如何延迟useLayoutEffect 直到检索到数据?
我在我的应用程序中经常使用useEffect 来检索数据并显示我需要的信息。我尝试在钩子useEffect 或useLayoutEffect 中同时执行这两个操作(检索数据并创建图表),但它不起作用。在使用useLayoutEffect之前我不能使用条件,也尝试过...
const AmChart = (props) => {
const chartRef = useRef(null);
const [data,setData] = useState([]);
const [startDate,setStartDate] = useState(new Date());
const [endDate,setEndDate] = useState(new Date());
useEffect(() => {
let from = startDate.getFullYear().toString() + ('0' + (startDate.getMonth() + 1)).slice(-2) + ('0' + startDate.getDate()).slice(-2);
let to = endDate.getFullYear().toString() + ('0' + (endDate.getMonth() + 1)).slice(-2) + ('0' + endDate.getDate()).slice(-2);
dataService.getData(from,to)
.then(response => {
setData(response.data);
});
},[]);
useLayoutEffect(() => {
let x = am4core.create("chartdiv", am4charts.XYChart);
// ... creation of the chart
chart.data = data;
// ... creation of the chart
chart.current = x;
return () => {
x.dispose();
};
}, []);
return (
<div id="chartdiv" style={{ width: "100%", height: "500px" }}></div>
);
}
【问题讨论】:
-
为什么需要使用
useLayoutEffect来创建图表?你不能只在一个单独的方法中创建它,然后将此方法作为你的 useEffect 的返回值调用吗?
标签: reactjs amcharts use-effect