延迟 React Hook useLayoutEffect 直到 useEffect 完成?
Delay React Hook useLayoutEffect until useEffect is done?
我有一个组件,我在其中使用挂钩 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(()=>{}, [data])
您应该将 'data' 添加到 useEffect 的依赖项列表中。欲了解更多信息,请阅读这篇文章:Docs on useEffect conditional firing
我有一个组件,我在其中使用挂钩 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(()=>{}, [data])
您应该将 'data' 添加到 useEffect 的依赖项列表中。欲了解更多信息,请阅读这篇文章:Docs on useEffect conditional firing