【问题标题】:Delay React Hook useLayoutEffect until useEffect is done?延迟 React Hook useLayoutEffect 直到 useEffect 完成?
【发布时间】:2020-08-03 13:34:37
【问题描述】:

我有一个组件,我在其中使用钩子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>
    );
}

【问题讨论】:

  • 为什么需要使用useLayoutEffect 来创建图表?你不能只在一个单独的方法中创建它,然后将此方法作为你的 useEffect 的返回值调用吗?

标签: reactjs amcharts use-effect


【解决方案1】:

您应该将“数据”添加到 useEffect 的依赖项列表中。更多信息请阅读这篇文章:Docs on useEffect conditional firing

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 2020-01-07
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 2013-08-31
      • 1970-01-01
      相关资源
      最近更新 更多