簡體   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