【问题标题】:How to cleanup an async funtion on componentDidUpdate using hooks如何使用钩子清理 componentDidUpdate 中的异步函数
【发布时间】:2020-02-09 00:00:51
【问题描述】:

我有一个组件,在其安装时,我订阅了一个套接字(异步任务),并且我必须在卸载时取消订阅(异步)。当组件更新时,我必须取消订阅旧套接字并订阅新套接字。我不确定如何使用反应钩子来做到这一点。附上一个示例代码框以供参考。

https://codesandbox.io/s/clever-robinson-h0gq5

【问题讨论】:

  • <Link to="/didMount">SimulateDidMount</Link> 上,您需要放置其他组件而不是应用程序组件。因为当您切换 url 时,应用程序组件会再次呈现......实际上并没有卸载。

标签: reactjs redux components react-hooks lifecycle


【解决方案1】:

我不确定您希望如何在沙箱中实现代码,但我认为在效果中调用和异步任务您可以这样做:

useEffect(() => {
  const timeout = async (msg, time) => {
    await setTimeout(() => {
      console.log(msg);
    }, time);
  }
  timeout("subscribed to websocket", 2000);
  return () => {
    timeout("unsubscribed to websocket", 3000);
  };
}, [match]);

要在useEffect 中使用async await,您需要在函数中声明它并从那里调用它。

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 2021-09-26
    • 2019-08-02
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多