延迟React Hook useLayoutEffect直到useEffect完成



我有一个组件,在该组件中我使用钩子useEffect从API检索数据。我想使用AMCharts在图表中显示数据。我的问题是,我需要使用钩子useLayoutEffect来创建图表,而图表是基于用useEffect检索到的数据。。。当我的图表被渲染时,我还没有数据,我的图表是空的。如何将useLayoutEffect延迟到检索到数据?

我在应用程序中经常使用useEffect来检索数据并显示我需要的信息。我尝试在挂钩useEffectuseLayoutEffect中同时执行这两项操作(检索数据和创建图表(,但都不起作用。在使用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>
);
}

您应该将"data"添加到useEffect的依赖项列表中。欲了解更多信息,请阅读本文:关于useEffect条件发射的文档

如果您需要钩子在数据更改时完成工作,请将数据状态添加到依赖项数组中。

useLayoutEffect(()=>{}, [data])

最新更新