【问题标题】:setState: can only update a mounted or mounting component react native /undefined is not an objectsetState: 只能更新一个挂载或挂载的组件 react native /undefined is not an object
【发布时间】:2017-05-26 18:03:35
【问题描述】:

每当我的互联网连接不好时,我都会不断收到此警告(我不确定这是不是发生这种情况的正确原因)。 我在反应本机应用程序(iOS/android)中显示来自 Firebase 数据库的数据的页面中得到了这个。 PS:我不考虑制作离线模式(这不是必需的)。 我正在与您分享我在其中一个页面中使用的代码(在所有页面中都非常相似)

代码

    constructor(props) {
            super(props);
            this.state = {
                dataSource: new ListView.DataSource({
                    rowHasChanged: (row1, row2) => row1 !== row2,
                })
            };

            this.itemsRef = this.getRef().child('path');

        }

        getRef() {
            return firebaseApp.database().ref();
        }
        componentDidMount() {
            this.listenForItems(this.itemsRef);
        }
        listenForItems(itemsRef) {

            itemsRef.on('value', (snap) => {
                if (snap.val()) {
                    var items = [];
                    snap.forEach((child) => {
                        items.push({
                            text : child.val().text,
                            title: child.val().title,
                            key: child.key
                        });
                    });

 this.setState({dataSource: this.state.dataSource.cloneWithRows(items)});
                }

            });

        }

        render() {
            return (
                <View>
                    <ListView
                        automaticallyAdjustContentInsets={true}
                        dataSource={this.state.dataSource}
                        renderRow={this._renderItem.bind(this)}/>
                </View>

            );
        }

        _renderItem(item) {
            return (
                <View>
                    <Text>{item.title}</Text>
                    <Text>{item.text}</Text>
                </View>
            );
        }
    }

这是我不断收到的警告:

它确实提到了组件的名称,但我仍然不知道这可能是什么原因

更新:我尝试了这个建议的解决方案:

componentWillUnmount() {
        this.itemRef.off();
    }

事实上,我有一个后退按钮,可以从一个页面更改为另一个页面(每个页面都有自己的路径和从 Firebase 提取的数据,但代码相似),我收到此错误:this.itemRef 在每个页面中都不同。 但我收到此错误: 任何想法或建议..谢谢你

【问题讨论】:

    标签: javascript firebase react-native try-catch warnings


    【解决方案1】:

    当您使用on() 订阅引用时,您将在数据库路径被修改时收到通知,在卸载组件时也会发生这种情况。为了防止出现此警告,您必须在 call off()componentWillUnmount 上使用相同的数据库引用

    componentWillUnmount() {
      this.itemsRef.off();
    }
    

    【讨论】:

    • 谢谢你..我试过你的,这是我的另一个错误..请查看更新..再次感谢你
    • 我打错了,是this.itemsRef.off()
    猜你喜欢
    • 2016-05-22
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多