繁体   English   中英

React:ComponentDidMount 中的 SetInterval 导致错误“警告:无法在未安装的组件上执行 React 状态更新。”

[英]React: SetInterval in ComponentDidMount causing error "Warning: Can't perform a React state update on an unmounted component."

我想为我的 React 应用程序中的组件添加打字效果,我正在使用setInterval来做到这一点。 一切正常,但我收到以下错误:

Warning: Can't perform a React state update on an unmounted component. 
This is a no-op, but it indicates a memory leak in your application. 
To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method

该函数从componentDidMount()开始,所以我不明白为什么它说我正在更新一个未安装的组件。 我尝试在componentWillUnmount()添加clearInterval() componentWillUnmount()但错误仍然显示。

代码:

componentDidMount = () => {
    this.typeText();
}

componentWillUnmount(){
    console.log(this.state.intervalId);
    clearInterval(this.state.intervalId);
}

typeText = () => {
    const sp = (text,key) => <span key={key} style={{whiteSpace: 'pre-line'}}>{text}</span>;
    const results = this.state.screenText;
    let start = 0;
    let cursor = 0;
    const intervalId = setInterval(() => {
        if (results.length) results.pop();
        const str = this.state.text.slice(start,cursor);
        const span = sp(str,cursor);
        results.push(span);
        this.setState({screenText:results});
        start = Math.floor((cursor / 80));
        cursor += 1;
        if (cursor > this.state.text.length) clearInterval(intervalId);  
    },5);

    this.setState({intervalId: intervalId});       
    console.log(this.state.intervalId);  
}
render() {
    return <span id="typing"> {this.state.screenText}</span> 
}

我认为您的代码的问题在于您将intervalId保存在组件的状态中。
您可能知道,当您调用setState它会导致rerender
您可以将您的intervalId保存在类的属性中。
请考虑您的代码中的这些更改:

  1. 像这样在类中定义一个属性
    class MyClsss extends React.component{ intervalId = ""; ... }
  2. 像这样在此属性中保存您的间隔 ID
     this.intervalId = setInterval(...)
  3. 以这种方式在任何地方清除您的间隔
    clearInterval(this.intervalId);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM