React Native - 只能更新已安装或安装的组件

时间:2016-04-11 00:00:51

标签: meteor react-native

我尝试使用react-native驱动程序从meteor订阅到ddp。在componentDidMount期间,它给了我例外

Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.

这是我的代码

    getInitialState: function() {
        return {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => !_.isEqual(row1, row2),
            }),
            loaded: false,
        };
    },
    componentDidMount: function() {
        console.log('component mounted');
        console.log(this.props['actor']);

        ddp.initializeWithSubscribe(() => {
            ddp.subscribe('select-all-meals-by-restaurant', [this.props['actor']['obj']['_id']]);
        });

        var ddpClient = ddp.connection;
        var observer = ddpClient.observe('meals');

        observer.added = () => this.updateRows(_.cloneDeep(_.values(ddpClient.collections.meals)));
        observer.changed = () => this.updateRows(_.cloneDeep(_.values(ddpClient.collections.meals)));
        observer.removed = () => this.updateRows(_.cloneDeep(_.values(ddpClient.collections.meals)));
    },

    /*------------------------------------------------------------------------------
     * Util function for watching data
     *-----------------------------------------------------------------------------*/
    updateRows: function(rows) {
        console.log('rows :' + rows);

        this.setState({
            dataSource: this.state.dataSource.cloneWithRows(rows),
            loaded: true,
        });
    },

你能建议我解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:0)

这解释了发生了什么以及如何解决它:

https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html

基本上,在卸载组件后,您将收到更新。您需要使用componentWillUnmount取消订阅Meteor的更改。