2016-09-29 179 views

回答

22

由於isMounted()被正式棄用,您可以在您的組件做到這一點:

componentDidMount() { 
    this._ismounted = true; 
} 

componentWillUnmount() { 
    this._ismounted = false; 
} 

維護自己state變量的這種模式是ReactJS文檔中詳細介紹:https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html

+1

感謝您對文檔的建議...只需在componentDidMount中將_isMounted屬性設置爲true,並在componentWillUnmount中將其設置爲false ...但是,使用此屬性。setState({mounted:false});可能會觸發太晚,以防止警告,因爲狀態變化不會立即發生 - 最好只是使用類屬性爲此... this.mounted = false - 謝謝你,這指出我在正確的方向 – danday74

+0

@ danday74,是啊你是正確的。當我寫出答案時,我可能錯過了這一點。考慮upvoting如果它的幫助 –

+0

是的我在10天前upvoted :) – danday74

1

我發現,組件將被卸載,生成填充此變量

if(!this._calledComponentWillUnmount)this.setState({vars});

1

我到了這裏是因爲我正在尋找停止polling API的方法。

react docs確實涵蓋了websocket的情況,但不包括輪詢的情況。

我周圍

// React component 
let allowPolling = true 

React.createClass({ 
    poll() { 
     if (!allowPolling) { 
      return 
     } 
     // otherwise, call the api 
    } 
    componentWillMount() { 
     allowPolling = true 
    } 
    componentWillUnmount() { 
     allowPolling = false 
    } 
}) 

它的工作的工作方式。希望它可以幫助

請讓我知道,如果你們知道任何失敗的測試情況下,此=]

9

我認爲Shubham答案是對於那些需要轉變他們的代碼停止使用人們的反應提出了一個解決辦法isMounted反模式。

這不一定是壞事,但它是值得列出真正的解決方案,以解決這個問題。

The article linked by Shubham提供2條建議以避免這種反模式。您需要的一個取決於您在卸載組件時爲什麼要調用setState。

,如果您使用的是您的組件通量商店,你必須在componentWillUnmount退訂

class MyComponent extends React.Component { 
    componentDidMount() { 
    mydatastore.subscribe(this); 
    } 
    render() { 
    ... 
    } 
    componentWillUnmount() { 
    mydatastore.unsubscribe(this); 
    } 
} 

如果使用ES6的承諾,你可能需要包裝自己的諾言,以使它可以取消。

const cancelablePromise = makeCancelable(
    new Promise(r => component.setState({...}})) 
); 

cancelablePromise 
    .promise 
    .then(() => console.log('resolved')) 
    .catch((reason) => console.log('isCanceled', reason.isCanceled)); 

cancelablePromise.cancel(); // Cancel the promise 

鏈接的文章中瞭解更多關於makeCancelable

總之,不要嘗試通過設置變量和檢查組件是否已裝入來修補此問題,請轉到問題的根源。如果您能提出任何疑問,請與其他常見情況進行評論。

相關問題