【问题标题】:Can we use life cycle method in function component? vise versa life cycle hooks in class component?我们可以在函数组件中使用生命周期方法吗?反之亦然类组件中的生命周期挂钩?
【发布时间】:2022-01-05 18:35:35
【问题描述】:

我们可以在函数组件中使用生命周期方法吗?反之亦然的生命周期是否挂钩类内组件?如果是,如何,请分享任何链接。

【问题讨论】:

标签: reactjs methods react-redux react-hooks components


【解决方案1】:

是的,您可以借助useEffect钩子在功能组件中使用生命周期方法。

useEffect 钩子可用于复制生命周期行为。例如:

componentDidMount:

componentDidMount() {
  window.addEventListener('unhandledRejection', handler);
}

功能组件等价

useEffect(() => {
    window.addEventListener('unhandledRejection', handler);
}, [])

componentWillUnmount:

  componentWillUnmount() {
    alert('The component is going to be unmounted');
    window.removeEventListener('unhandledRejection', handler);
  }

功能组件等价

useEffect(() => {
    window.addEventListener('unhandledRejection', handler);
    return () => {
       alert('The component is going to be unmounted');
       window.removeEventListener('unhandledRejection', handler);
    }
}, [])

componentDidUpdate:

componentDidUpdate(prevProps, prevState) {
     const { counter } = this.props;
     if (this.props.counter !== prevState.counter) {
      // some action here
     }
}

功能组件等价

useEffect(() => {
     // action here
}, [props.counter]); // checks for changes in the values in this array

【讨论】:

  • 嗨@Rajendra Singh Adhikari,我很高兴你发现我的回答很有帮助:) 如果这个或任何答案已经解决了你的问题,请考虑通过单击复选标记接受它。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多