【问题标题】:In React, what is the difference these useEffect?在 React 中,这些 useEffect 有什么区别?
【发布时间】:2022-01-13 14:06:26
【问题描述】:
  useEffect(() => {
    return () =>
      setTimeout(() => set_current_focus(index_map[comp_index]), 1000);
  }, [comp_index]);

  useEffect(() => {
    return setTimeout(() => set_current_focus(index_map[comp_index]), 1000);
  }, [comp_index]);

根据我的测试,没有区别。

有人可以确认吗?

【问题讨论】:

  • useEffect 应该怎么做? set_current_focus 每当 comp_index 更改时 1 秒后?
  • 都不正确。 useEffect(() => {/*component created, set timer*/const timer=setTimeout(cb, delay);return () => {/*component destroyed, clear timer*/clearTimeout(timer)}})
  • 是的,没错

标签: reactjs use-effect


【解决方案1】:

useEffectsn-ps 都不正确。

传递给useEffect 的回调返回的值应该是一个用于清理事物的函数(比如在你的情况下清除超时)。

所以正确的用法是这样的:

useEffect(() => {
  const timeout = setTimeout(
    () => set_current_focus(index_map[comp_index]),
    1000
  );

  return () => clearTimeout(timeout);
}, [comp_index]);

【讨论】:

    猜你喜欢
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2013-01-16
    • 1970-01-01
    • 2018-08-25
    • 2012-09-27
    相关资源
    最近更新 更多