React Hooks setTimeout 和 clearTimeout

React Hooks setTimeout and clearTimeout

我阅读了 'Using the Effect Hook' 文档,但我仍然很难清除 useEffect 钩子的副作用。具体来说,我有这个 class 组件,我想了解如何使用 useEffect 挂钩将它转换为函数组件。

class Alert extends PureComponent {
  componentDidMount() {
    this.handleSetTimeout()
  }

  componentDidUpdate() {
    this.handleClearTimeout()
    this.handleSetTimeout()
  }

  componentWillUnmount() {
    this.handleClearTimeout()
  }

  handleSetTimeout = () => {
    const { alert: { id, ttl }, handlePopAlert } = this.props
    if (!ttl) return
    this.timeout = setTimeout(() => handlePopAlert(id), ttl)
  }

  handleClearTimeout = () => {
    if (!this.timeout) return
    clearTimeout(this.timeout)
    this.timeout = null
  }

  render() { return (...) }
}

传递给 useEffect 的函数可能 return 清理 function.The 在组件从 [=23= 中删除之前清理函数 运行s ] 以防止内存泄漏。此外,如果组件渲染多次(通常会这样做),则在执行下一个效果之前会清除上一个效果。

在您的情况下,由于需要根据从 props 传递的 id 调用 handlePopAlert 函数,因此只要您传递的 id, ttl 发生更改,效果就需要 运行 useEffect 的第二个参数作为 id 和 ttl

const Alert = (props) => {
  const { alert: { id, ttl }, handlePopAlert } = this.props
  useEffect(() => {
    const timeout = setTimeout(() => {
       handlePopAlert(id)
    }, ttl)
    return () => {
       clearTimeout(timeout);
    }
  }, [id, ttl]);

  return (...)
}