当我的React app中的路由发生变化时,我的clearInterval()和应用程序中断了

问题描述 投票:3回答:2

我正在使用React-router-dom开发React应用程序。

我有一个菜单上有一些react-router-dom的<NavLink />,每个都带我到不同的路线。

在我的主要路线path="/"我有一个chartComponent图表,随着随机数据不断变化,像这样:this.chartChangeId = setInterval(()=> this.setState(data), 1500)

在我添加之前:

componentWillUnmount(){
    clearInterval(this.chartChangeId);
}

to chartComponent我的应用程序没有中断,但我收到此错误:

警告:只能更新已安装或安装的组件。这通常意味着您在已卸载的组件上调用了setState,replaceState或forceUpdate。这是一个无操作。请检查BrainWaveChart组件的代码。

所以我把它添加到生命周期中。

但现在,当我点击其中一个<NavLink />去一个不同的路线我的应用程序中断,我得到这个错误:

未捕获的TypeError:timeout.close不是exportWinsChart.componentWillUnount(brainwaveChart.jsx:116)中的exports.clearTimeout.exports.clearInterval(main.js:14)中的函数,位于callUonentWillUnmountWithTimer(vendor_f02cab182c1842c98837.js:45235),位于HTMLUnknownElement.callCallback( vendor_f02cab182c1842c98837.js:37015)在Object.invokeGuardedCallbackDev(vendor_f02cab182c1842c98837.js:37054)在invokeGuardedCallback(vendor_f02cab182c1842c98837.js:36911)在safelyCallComponentWillUnmount(vendor_f02cab182c1842c98837.js:45242)在commitUnmount(vendor_f02cab182c1842c98837.js:45368)在commitNestedUnmounts(vendor_f02cab182c1842c98837.js :45404)unmountHostComponents(vendor_f02cab182c1842c98837.js:45687)

我做错了吗?

javascript reactjs setinterval react-router-dom
2个回答
4
投票

即使你清除了间隔,()=> this.setState(data)也在执行,因为它已经在内存中并且在异步堆栈中。您需要做的是检查组件是否存在,然后才更新状态。最简单的事情是做什么

const {clearInterval, setInterval} = window;
class Comp extends React.Component {
  constructor(props) {
    super(props);
    this.mounted = false;
    this.interval = setInterval(() => {
      if(this.mounted) this.setState();
    })
  }
  componentWillMount() {
    this.mounted = true;
  }
  componentWillUnmount() {
    this.mounted = false;
    clearInterval(this.interval);
  }
}

然而,这更像是反模式。正确的方法是不要在Ajax中使用setState。 https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html


0
投票

您的IDE可能会自动为您导入{ clearInterval }, 这就是导致问题的原因。 请检查您的文件中是否有import { clearInterval } from ....声明, 并删除它。 它发生在一些IDE中。 此链接提供更多信息: https://github.com/angular/angular/issues/12400

© www.soinside.com 2019 - 2024. All rights reserved.