【问题标题】:The issue of React Lifecycle in a Functional Component (Data undefined in the child component)功能组件中的 React Lifecycle 问题(子组件中的数据未定义)
【发布时间】:2021-07-31 09:18:12
【问题描述】:

当我尝试从父组件调用后端 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>
  );
};

所以我寻找一种方法来执行首先从父组件调用后端的函数,以便子组件可以访问数据。

【问题讨论】:

  • 当您将一个空数组传递给useEffect 时,它只会在挂载和卸载时运行。尝试将您的日志语句放在 useEffect 方法之外。
  • YEH 兄弟,这就是问题所在,因为空数组在组件的挂载中只被触发一个,但是在添加依赖项时就像在更新一样,谢谢

标签: reactjs react-hooks react-context react-functional-component react-lifecycle


【解决方案1】:

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]);

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    相关资源
    最近更新 更多