当我的 React 应用程序中的路由更改时,我 clearInterval() 和应用程序中断

IT技术 javascript reactjs setinterval react-router-dom
2021-05-05 02:07:07

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

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

在我的主要途径path="/"我有chartComponent与上用随机数据发生变化,这样保持一个图表:this.chartChangeId = setInterval(()=> this.setState(data), 1500)

在我添加这个之前:

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

chartComponent我的应用程序没有中断,但我收到了这个错误:

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

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

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

未捕获的类型错误:timeout.close 不是一个函数 atexports.clearTimeout.exports.clearInterval (main.js:14) at BrainWaveChart.componentWillUnmount (brainwaveChart.jsx:116) at callComponentWillUnmountWithTimer (vendor_f02cab182c1842c94callCallback(HTML) (HTML): 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)

我做错了吗?

2个回答

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

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