javascript - 当我的 React 应用程序中的路线发生变化时,我 clearInterval() 和应用程序中断

标签 javascript reactjs setinterval react-router-dom

我正在使用 React-router-dom 开发一个 React 应用

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

在我的主要路线 path="/" 中,我有一个 chartComponent,其中的图表随随机数据不断变化,如下所示:this.chartChangeId = setInterval(()=> this.setState(data), 1500)

在我添加之前:

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

对于chartComponent,我的应用没有中断,但出现了这个错误:

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op. Please check the code for the BrainWaveChart component.

所以我将其添加到生命周期中。

但现在,当我点击其中一个 <NavLink /> 转到另一条路线时,我的应用程序中断,并且出现此错误:

Uncaught TypeError: timeout.close is not a function at exports.clearTimeout.exports.clearInterval (main.js:14) at BrainWaveChart.componentWillUnmount (brainwaveChart.jsx:116) at callComponentWillUnmountWithTimer (vendor_f02cab182c1842c98837.js:45235) at HTMLUnknownElement.callCallback (vendor_f02cab182c1842c98837.js:37015) at Object.invokeGuardedCallbackDev (vendor_f02cab182c1842c98837.js:37054) at invokeGuardedCallback (vendor_f02cab182c1842c98837.js:36911) at safelyCallComponentWillUnmount (vendor_f02cab182c1842c98837.js:45242) at commitUnmount (vendor_f02cab182c1842c98837.js:45368) at commitNestedUnmounts (vendor_f02cab182c1842c98837.js:45404) at unmountHostComponents (vendor_f02cab182c1842c98837.js:45687)

我做错了吗?

最佳答案

()=> 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

关于javascript - 当我的 React 应用程序中的路线发生变化时,我 clearInterval() 和应用程序中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47923656/

相关文章:

javascript - 当鼠标至少移动一次时创建 PHP session

javascript - 为什么我在 Laravel 框架中收到此内部服务器错误?

javascript - 设置 Ember.TextField 的 ID

reactjs - React Router 与 React 16.6 Suspense "Invalid prop ` 组件`类型为 `object` 提供给 `Route` ,预期为 `function` 。”

javascript - Monaco Editor react Electron 卡在负载上

网格中灯光序列的Javascript问题

javascript - 为了性能更好,两个函数在同一个 setInterval() 中还是两个不同的 setInterval 中? - JavaScript

javascript - Firebase 函数 setInterval 和 clearInterval 分别调用

javascript - 设置间隔和清除间隔

javascript - 如何为react-table中的一行提供2个不同的事件