【问题标题】:Condition inside setInterval in functional component功能组件中 setInterval 内的条件
【发布时间】:2020-11-09 13:54:45
【问题描述】:

如果状态变量 can_update 为真,我在 useEffect 中设置了一个间隔,以每 33 秒更新一次数据。 can_pdate 的初始值 = true。问题是,即使我将 can_update 更改为 false(使用 disable_update 函数),在 update_groups 函数中它仍然为 true。

  const [can_update, set_can_update] = useState(true);
  const [groups, set_groups] = useState([]);

  const intervalRef = useRef();

  useEffect(() => {
    update_groups();
    const update_interval = setInterval(() => {
      update_groups();
    }, 33000);
    intervalRef.current = update_interval;
    return () => {
      clearInterval(intervalRef.current);
    };
  }, [project_data.id]);

  const update_groups = () => {
    if (can_update) {
      UI.get(`/project/${project_data.id}/controllers/`).then(
        (data) => {
          set_groups(data.groups);
        },
        (error) => {
          console.log("Не удалось загрузить список групп");
        },
      );
    }
  };

  const enable_update = () => {
    set_can_update(true);
  };

  const disable_update = () => {
    set_can_update(false);
  };

我已经尝试将条件移入

setInterval: `const update_interval = setInterval(() => {
    if (can_update){ update_groups()};
}

并将setInterval 替换为递归setTimeout。没有变化。

我在一个类组件中有一些类似的代码,似乎没有任何这样的问题。

【问题讨论】:

  • 看起来你的 useEffect 钩子应该包含 update_groups 函数作为依赖项(而不是 project_data.id)。您还需要将update_groups 包装在带有相关依赖项的useCallback 钩子中(can_updateproject_data.id)。
  • 另外,就其价值而言,您似乎不需要为intervalRef 使用参考。只需一个常规变量就足够了。

标签: javascript reactjs setinterval react-functional-component


【解决方案1】:

您需要将can_update 添加到useEffect 部门,否则

所有值 从改变的组件范围(例如道具和状态) 时间和效果使用的时间。 https://reactjs.org/docs/hooks-effect.html

在您的情况下,useEffect 被调用一次,在其中每 33 秒调用一次函数 update_groups,其作用域值为 can_update = true

React.useEffect(() => {
    if (can_update) {
        update_groups();
        const update_interval = setInterval(() => {
            update_groups();
        }, 33000);
        intervalRef.current = update_interval;
        return () => {
            clearInterval(intervalRef.current);
        };
    }
}, [project_data.id, can_update]);

const update_groups = () => {
    UI.get(`/project/${project_data.id}/controllers/`).then(
        data => {
            set_groups(data.groups);
        },
        error => {
            console.log('Не удалось загрузить список групп');
        },
    );
};

【讨论】:

    猜你喜欢
    • 2020-07-06
    • 2023-01-17
    • 2021-08-06
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 2021-06-12
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多