【问题标题】:React Native - setState Warning on second mountReact Native - 第二次挂载时出现 setState 警告
【发布时间】:2016-06-25 00:31:55
【问题描述】:

请检查以下代码:

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(…) 只能更新挂载或挂载的组件…

【问题讨论】:

    标签: react-native flux 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 1970-01-01
      • 2016-10-01
      • 2016-02-22
      • 1970-01-01
      • 2019-02-11
      • 2016-03-23
      • 1970-01-01
      • 2016-07-15
      相关资源
      最近更新 更多