React Lifecycle in a Functional Component (Data undefined in the child component) 的问题

The issue of React Lifecycle in a Functional Component (Data undefined in the child component)

我 运行 当我尝试从父组件调用后端 api 时遇到问题,调用结果在子组件中始终为 null。 这是我的实现: 父组件:

const Parent = () => {
  const { loadFiData, fiData, year } = useContext(DashboardContext);

  useEffect(() => {
    let loading = true;
    
    if (loading) loadFiData();

    return () => (loading = false);
  }, [year]);

  return (
    <div className="mt-5">
      <Child />
    </div>
  );
};

子组件:

const Chart1 = () => {
  const { fiData } = useContext(DashboardContext);

  useEffect(() => {
    if (fiData) {
      console.log('there is a data');
    } else {
      console.log('there is no data');
    }
  }, []);

  return (
    <h1>Child</h1>
  );
};

所以我想办法先执行从父组件调用后端的函数,以便子组件可以访问数据。

Chart1/Child 组件中添加 fiData 作为 useEffect 的依赖项。那么 useEffect 里面的代码应该 运行 2 次。它应该首先控制台 there is no data 并且当请求在上下文中完成时,然后它应该控制台 there is a data.

useEffect(() => {
    if (fiData) {
        console.log('there is a data');
    } else {
        console.log('there is no data');
    }
}, [fiData]);