首页 > 解决方案 > 如何将 componentDidMount() 和 componentWillUnmount 转换为 useEffect()?

问题描述

我正在尝试创建一个弹出窗口,通知用户在他们离开时按保存进度。我需要将以下代码转换为钩子:

class Prompt extends React.Component {
  componentDidMount() {
    window.addEventListener('beforeunload', this.beforeunload.bind(this));
  }

  componentWillUnmount() {
    window.removeEventListener('beforeunload', this.beforeunload.bind(this));
  }

  beforeunload(e) {
    if (this.props.dataUnsaved) {
      e.preventDefault();
      e.returnValue = true;
    }
  }

  render() {...}
}

我知道我应该使用 useEffect() 但不确定如何,因为我通常不熟悉钩子。特别是我不确定将什么作为第二个参数,因为钩子不喜欢 this.bind。任何帮助将不胜感激。

标签: javascriptreactjs

解决方案


根据反应文档:

如果熟悉 React 类生命周期方法,可以将 useEffect Hook 视为 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合。

所以 componentDidMount 将是:

useEffect(() => { // yourCode },[])

并且由于 componentWillUnmout 用于清理请参阅 React Docs,您可以像这样使用它作为回报:

useEffect(() => {
  window.addEventListener('beforeunload', () => {});

  return () => {
    window.removeEventListener('beforeunload', () => {})
  }
}, [])

推荐阅读