when route changes in my React app I clearInterval() and app breaks
我正在使用React-router-dom开发一个React应用程序。
我有一个菜单,其中包含一些react-router-dom的
在我的主要路线
在我添加以下内容之前:
1 2 3 | 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.
所以我将其添加到生命周期中。
但是现在,当我单击
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)
我做错了吗?
即使清除间隔,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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/ismount-antipattern.html
您的IDE可能会自动为您导入
这就是导致问题的原因。
请检查文件中是否有
并删除它。
它发生在某些IDE中。
该链接提供了更多信息:
https://github.com/angular/angular/issues/12400