2017-03-29 121 views
0

問題:爲什麼在組件不再由父組件渲染後引發此警告?我錯過了需要做什麼來卸載這個組件,而不是僅僅過濾作爲道具傳遞給組件層次結構的存儲狀態?正確卸載React組件

我已經看到這種情況出現很多,但解決方案通常是涉及從組件中取消訂閱redux存儲庫;但是,此組件未連接到商店,只是頂級容器。

  • remove操作只是過濾存儲狀態以除去負責當前組件的數組元素。
  • refresh動作當前只是一個模擬UI組件中的UI動畫事件。的setState(...):只能更新一安裝或安裝組件時,我調用refresh行動

警告後刪除Feed組件

  • 警告只拋出。這通常意味着您在卸載的組件上調用了setState()。這是一個沒有操作。請檢查Feed組件的代碼。

  • // @flow 
    // Feed.js 
    
    import React, { Component } from 'react' 
    import type { FeedType, FeedState } from '../../utils/types' 
    import { remove, refresh } from '../../actions/redux-actions' 
    import RssEventList from '../containers/RssEventList' 
    
    const cardColors: Array<string> = ['red', 'orange', 'olive', 'green', 'blue', 'yellow'] 
    
    export default class Feed extends Component { 
        props: FeedType 
        state: FeedState 
    
        constructor(props: *) { 
        super(props) 
    
        this.state = { 
         reloading: false 
        } 
        } 
    
        refresh() { 
        this.setState({ reloading: true }) 
        setInterval(() => this.setState({ reloading: false }), 4000) 
        this.props.dispatch(refresh(this.props.link)) 
        } 
    
        remove() { 
        this.props.dispatch(remove(this.props.link)) 
        } 
    
        render() { 
        const color: string = cardColors[Math.floor(Math.random() * cardColors.length)] 
    
        return (
         <div className={`ui ${color} card`}> 
         <div className="content"> 
          <div className="ui header"> 
          {this.props.title} 
          <a className="source link" href={this.props.link} target="_blank"> 
           <i className="linkify right floated icon"></i> 
          </a> 
          </div> 
          <div className="meta"> 
          {this.props.description} 
          </div> 
         </div> 
         <div className="content"> 
          <RssEventList reloading={this.state.reloading} events={this.props.feed} /> 
         </div> 
         <div className="extra content"> 
          <span className="left floated" onClick={() => this.refresh()}> 
          <i className="refresh icon"></i> 
          Refresh 
          </span> 
          <span className="right floated" onClick={() => this.remove()}> 
          <i className="cancel icon"></i> 
          Remove 
          </span> 
         </div> 
         </div> 
        ) 
        } 
    } 
    

    如果有幫助,這裏是組件層次結構的示意圖:

    App (connected to store) 
    |- Header 
    |- FilterBar 
    |- FeedList 
        |- Feed 
         |- RssEventList 
         |- RssEvent 
        |- AddCard 
    

    回答

    1

    的問題是,你是不是在存儲元件的間隔組件時會卸載將其刪除。因此,即使在卸載組件後,間隔仍將繼續被調用。你需要刪除它與clearInterval()

    export default class Feed extends Component { 
        refresh() { 
        this.myInterval = setInterval(() => this.setState({ reloading: false }), 4000) 
        } 
    
        componentWillUnmount() { 
        clearInterval(this.myInterval); 
        } 
    } 
    
    +0

    哇,愚蠢的錯誤在我的部分!謝謝 –