React Native - 第二次安装时的setState警告

时间:2016-03-10 09:03:12

标签: react-native flux 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_TEAMS Event由另一个Component触发。

如果我第一次渲染组件,一切正常。但是,如果我弹出页面并在此页面上再次导航,我收到了此警告:

  

警告:setState(...)只能更新已安装或安装的组件......

1 个答案:

答案 0 :(得分: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();
}