简体   繁体   English

React Native 和 Firebase 实时数据库

[英]React Native and Firebase Real Time Database

I am having 2 problems using React Native and Firebase Real Time Database.我在使用 React Native 和 Firebase 实时数据库时遇到了 2 个问题。

  • When I add something to the list with the text input, all the list itens are duplicated except the item that I just added, this problem is only solved when I refresh the app screen.当我使用文本输入向列表中添加某些内容时,除了我刚刚添加的项目之外,所有列表项都会重复,只有在我刷新应用程序屏幕时才能解决此问题。

  • When I remove something from firebase dashboard or other client, the list is not updated real time.当我从 firebase 仪表板或其他客户端删除某些内容时,列表不会实时更新。

  import React, {useState, Component} from 'react';
  import {
    Text,
    View,
    Switch,
    StyleSheet,
    FlatList,
    TextInput,
    Button,
    TouchableOpacity,
    SafeAreaView,
    VirtualizedList,
  } from 'react-native';

  import database from '@react-native-firebase/database';

  class MenuBreakFastScreen extends React.Component {
    state = {newItem: ''};
    state = {itens: []};

    componentDidMount() {
      let dbRef = database().ref('/cafe/itens/');
      this.listenerFirebase(dbRef);
    }

    listenerFirebase(dbRef) { 
      dbRef.on('value', dataSnapshot => {
        const newItens = JSON.parse(JSON.stringify(this.state.itens));
        dataSnapshot.forEach(child => {
          newItens.push({
            name: child.val().name,
            key: child.key,
          });
          this.setState({itens:newItens});
        });
      });
    }

    addItem() {
      if (this.state.newItem === '') {
        return;
      }
      database().ref('/cafe/itens/').push({
        name: this.state.newItem,
      });
      this.setState({
        newItem: '',
      });
    }

    render() {
      const {itens} = this.state;
      const {newItem} = this.state;
      const renderItem = ( {item}) => {
        return(
          <ItemAsset title={item.name}/>
        );
      }
      return (
        <SafeAreaView
          style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
          <FlatList 
          data={itens}
          renderItem={renderItem}
          keyExtractor={item => item.key}
          />
          <SafeAreaView style={{flexDirection: 'row'}}>
            <TextInput
              style={styles.input}
              onChangeText={text =>
                this.setState({
                  newItem: text,
                })
              }
              value={newItem}
            />
            <TouchableOpacity style={styles.Botao} onPress={() => this.addItem()}>
              <Text style={styles.BotaoTexto}>+</Text>
            </TouchableOpacity>
          </SafeAreaView>
        </SafeAreaView>
      );
    }
  }

  const styles = StyleSheet.create({
    texto: {
      fontSize: 35,
    },
    input: {
      color: '#000',
      fontSize: 22,
      borderWidth: 1,
      flex: 8,
      margin: 10,
    },
    BotaoTexto: {
      color: '#fff',
      fontSize: 22,
    },
    Botao: {
      backgroundColor: '#000',
      marginTop: 10,
      padding: 10,
      flex: 1,
      alignItems: 'center',
      margin: 10,
    },
    ListaContainer: {
      flexDirection: 'row',
      backgroundColor: '#000',
      flex: 1,
    },
    item: {
      backgroundColor: '#000',
      padding: 20,
      marginVertical: 8,
      marginHorizontal: 16,
      flexDirection: 'row',
    },
    title: {
      color: '#ffff',
      fontSize: 32,
    }, 
  });

  const ItemAsset = ( {title} ) => {
    return(
      <View style={styles.item}>
        <Text style={styles.title}>{title}</Text>
      </View>
    );
  }
  export default MenuBreakFastScreen;

When you are listen for real time changes on real-time database it will send all the items with snapshot when any data is changed.当您在实时数据库上侦听实时更改时,它会在任何数据更改时发送所有带有快照的项目。 That happens because you are listen for whole list, not only for a single item.发生这种情况是因为您正在收听整个列表,而不仅仅是单个项目。 Therefore you do not need to get the current list from state.因此,您不需要从 state 获取当前列表。 You just have to set the state with retrieved data.您只需使用检索到的数据设置 state。

   listenerFirebase(dbRef) { 
      dbRef.on('value', dataSnapshot => {
        const newItens = [];         // This should be initially empty array. That's all.
        dataSnapshot.forEach(child => {
          newItens.push({
            name: child.val().name,
            key: child.key,
          });
        });
        this.setState({itens:newItens});
      });
    }

After correcting this part the error you got when removing data will be also resolved.更正此部分后,您在删除数据时遇到的错误也将得到解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM