2016-03-10 25 views
0

請檢查如下代碼:陣營原住民 - 的setState警告在第二安裝

componentDidMount() { 
    /* 
    * Add listener 
    * The User has search for a team 
    */ 
    teamStore.addChangeListener("SEARCH_TEAMS", this.updateTeams.bind(this)); 
} 

componentWillUnmount() { 
    /* 
    * Remove Listener and clear the Store 
    */ 
    teamStore.removeChangeListener("SEARCH_TEAMS", this.updateTeams); 
    teamStore.resetTeams(); 
} 

/* 
* The API has find some new teams 
* Update the state and show the new teams in the listview 
*/ 

updateTeams() { 
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); 
    this.setState({dataSource: ds.cloneWithRows(teamStore.getAllTeams())}); 
} 

信息:該SEARCH_TEAMSEvent被另一Component觸發。

如果我第一次渲染組件,一切正常。但是,如果我彈出頁面,此頁面上再次導航我得到了這樣的警告:

警告:的setState(...)只能更新安裝或安裝組件...

回答

1

你沒有正確清除你的事件監聽器,因爲給出了不同的函數引用。這使得你的事件監聽器保持監聽,並在其中調用setState。

這裏有一個修復:

componentDidMount() { 
    // Save the function you want to listen with so you can remove it later 
    this.updateTeamsBound = this.updateTeams.bind(this); 
    teamStore.addChangeListener("SEARCH_TEAMS", this.updateTeamsBound); 
} 

componentWillUnmount() { 
    teamStore.removeChangeListener("SEARCH_TEAMS", this.updateTeamsBound); 
    teamStore.resetTeams(); 
}