2016-06-21 116 views
2

我設置下面的代碼。我應該如何清除componentWillUnmount中的狀態?

componentWillUnmount() { 
    this.setState({'modal':false}) or this.setState({}) 
} 

但狀態不明確。我怎樣才能做到這一點? 離開組件時我需要清除狀態。

+0

實際調用的方法是?例如,當您通過推動新屏幕導航到新屏幕時,它將不會被調用。只有當組件被移除時。 –

回答

1

React只改變傳入的鍵的狀態,所以如果你傳入一個空對象,結果將沒有任何改變。如果你有

{ 
    first: 1, 
    second: 2, 
    third: 3, 
} 

調用

狀態
setState({ 
    first: 10 
}) 

會導致你的狀態更新到

{ 
     first: 10, 
     second: 2, 
     third: 3, 
    } 

爲了清除狀態,以清除所有的至少一種方式它是明確地將所有的密鑰設置爲undefined,就像這樣

const blankState = {}; 
Object.keys(this.state).forEach(stateKey => { 
    blankState[stateKey] = undefined; 
}); 
this.setState(blankState); 

更多信息可以在React網站的文檔中找到。 https://facebook.github.io/react-native/docs/state.html