React Hooks setTimeout 和 clearTimeout

coc*_*ave 6 reactjs react-hooks

我阅读了“使用效果钩子”文档,但我仍然很难清除useEffect钩子的副作用。具体来说,我有这个类组件,我想了解如何使用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 (...) }
}
Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 12

传递给的函数useEffect可能会返回一个清理函数。清理函数在组件从 UI 中移除之前运行,以防止内存泄漏。此外,如果一个组件渲染多次(正如他们通常所做的那样),则在执行下一个效果之前会清除前一个效果。

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

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

  return (...)
}
Run Code Online (Sandbox Code Playgroud)