Firebase更新时,React Native数据未更新

时间:2018-12-04 11:09:07

标签: reactjs firebase react-native firebase-realtime-database

我正在做一个项目,我已经完成了99%,但是有一个问题。
为什么更新后数据没有变化?
在Firebase中,数据已更改,但我的列表仍显示以前的数据。

这是我的代码:

import React from 'react';
import { StyleSheet, Text, View, ListView,TouchableOpacity,Image,Alert,ActivityIndicator } from 'react-native';
import { Button, List, ListItem } from 'native-base'
import firebase from '../routes/set';

var data = []

export default class Menu extends React.Component {

  constructor(props) {
    super(props);

    this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })

    this.state = {
      listViewData: data,
      loading:false
    }
  }

  componentWillMount() {

    var that = this

    firebase.database().ref('/user').on('child_added', function (data) {
      var newData = [...that.state.listViewData]
      newData.push(data)
      that.setState({ listViewData: newData })
    })
  }

  async deleteRow(data,secId, rowId, rowMap) {

    await firebase.database().ref('user/' + data.key).set(null)
    rowMap[`${secId}${rowId}`].props.closeRow();
    var newData = [...this.state.listViewData];
    newData.splice(rowId, 1)
    this.setState({ listViewData: newData });

  }

  render() {
    return (

      this.state.listViewData<1?<ActivityIndicator/>:
      <View style={styles.container}>

        <List
          enableEmptySections
          dataSource={this.ds.cloneWithRows(this.state.listViewData)}
          renderRow={(data,secId,rowId,rowMap)=>
          <ListItem>
            <TouchableOpacity onLongPress={()=>
      Alert.alert(null,'data',
      [
     {text:'delete',onPress:()=>this.deleteRow( data,secId, rowId, rowMap)},
     {text:'edit',onPress:()=>this.props.navigation.navigate('Edit',{data:data,secId:secId,rowId:rowId,rowMap:rowMap})},
     {text:'cancel',onPress:()=>null}
      ])
            }>
              <View style={{flexDirection:'row', marginLeft:20,marginTop:20}}>
                <Image source={data.val().avatarSource} style={{width:50,height:50,borderRadius:30}}/>
                <View style={{flexDirection:'column',marginLeft:20}}>
                  <Text> {data.val().name}</Text>
                  <Text> {data.val().age}</Text>
                  <Text> {data.val().gender}</Text>
                  <Text> {data.val().dob}</Text>
                </View>
              </View>
            </TouchableOpacity>
          </ListItem>
          }


     renderRightHiddenRow={( secId, rowId, rowMap,data) =>
        <Button full danger onPress={() => this.deleteRow(secId, rowId, rowMap, data)}>
        </Button>

      }
      />
      <TouchableOpacity onPress={()=>this.props.navigation.navigate('Daftar')}>
        <Text>Insert</Text>
      </TouchableOpacity>
    </View>

    );
  }m
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
});

0 个答案:

没有答案