功能组件中 setInterval 内的条件

Condition inside setInterval in functional component

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

  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。没有变化。

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

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

all values from the component scope (such as props and state) that change over time and that are used by the effect. 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('Не удалось загрузить список групп');
        },
    );
};