【问题标题】:Method not being executed when leaving a component with componentWillUnmount()使用 componentWillUnmount() 离开组件时未执行方法
【发布时间】:2017-03-07 08:28:49
【问题描述】:

当我输入两个不同的组件时,我需要检查 Facebook 的到期日期和当前日期。 DashboardPages。两者都有这个:

componentWillMount() {
  const { linkedAccount, clearLinkedAccounts, getFacebookPages } = this.props
  const now = moment().format('YYYY-MM-DD HH:mm:ss')

  if (linkedAccount) {
    if (now < linkedAccount.expiresIn) {
      getFacebookPages()
    } else {
      clearLinkedAccounts()
    }
  }
}

componentWillUnmount() {
  const { linkedAccount, clearLinkedAccounts } = this.props
  const now = moment().format('YYYY-MM-DD HH:mm:ss')

  if (linkedAccount && now > linkedAccount.expiresIn) {
    clearLinkedAccounts()
  }
}

但只有在手动刷新页面时,clearLinkedAccounts() 才会被执行,通过运行componentWillMount,但在离开它之前,它不会。如有必要,我希望在进入另一条路线之前执行它。

【问题讨论】:

  • 你也可以提供 react 路由器代码吗?

标签: reactjs components


【解决方案1】:

刷新页面不像在同一个应用程序上下文中从一个页面转到另一个页面。 React router 允许您在 React 单个应用程序中使用 Link 之类的标签从一个页面转到另一个页面。这就是为什么 react 路由器如此有用的原因!

当您单击链接以转到带有Link 的另一个页面时,React 单个应用程序仍处于活动状态。因此,componentWillUnmount 将被调用,因为单个应用程序能够卸载组件。

当您刷新页面 (F5) 时,会加载一个新页面。结果,整个现有的单个应用程序被删除并提供给浏览器垃圾收集器。在这种情况下,您无法控制 React 组件。所以不可能调用componentWillUnmount,因为根本没有更多的组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多