Не удается повторно отобразить FlatList после удаления последнего элемента, хотя использовать extraData - React Native - PullRequest
0 голосов
/ 15 июня 2019

Я пытался перерисовать плоский список, но больше не могу обновляться,

Я получаю данные из БД в реальном времени и передаю их в Flatlist в качестве реквизита данных, и написать функцию для удаления элемента из списка и БД и работать очень хорошо, но когда я удаляю последний из списка, я не вижу пустой экран «Список» просто запас с последним, который я удалил, хотя он удален в БД!

код

import React, { Component } from 'react';
import { View, Text, StyleSheet, FlatList, ScrollView, TouchableOpacity } from 'react-native';
import firebase from "react-native-firebase";
import Icon from 'react-native-vector-icons/Ionicons';

class UserFavorites extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentUser: null,
            favorites: [],

        }
    }
    componentDidMount() {
        const currentUser = firebase.auth().currentUser.uid;
        this.setState({ currentUser });
        const favorites = firebase.database().ref(`favorites/${currentUser}`);
        favorites.on("value", (snapshot) => {
            let favorites = []
            snapshot.forEach((childSnapshot) => {
                favorites.push({
                    ProviderId: childSnapshot.val().ProviderId,
                    providerName: childSnapshot.val().providerName,
                    providerService: childSnapshot.val().providerService,
                });
                this.setState({ favorites })
            });
        });
    }
    _listEmptyComponent = () => {
        return (
            <View style={styles.container}>
                <Text style={{ alignSelf: "center" }}> No favorites Provider Found :O</Text>
            </View>
        )
    }
    render() {
        const { fav } = this.state;
        return (
            <View style={styles.container} >
                <FlatList data={this.state.favorites}
                    key={Math.random() * 1000}
                    contentContainerStyle={{ flexGrow: 1 }}
                    ListEmptyComponent={this._listEmptyComponent()}
                    extraData={this.state}
                    renderItem={({ item }) => {
                        return (
                            <ScrollView>
                                <TouchableOpacity>
                                    <View
                                        style={{
                                            flex: 1,
                                            paddingLeft: 15,
                                            paddingRight: 10,
                                            height: 105,
                                            alignItems: "center",
                                            backgroundColor: "#fafafa",
                                            flexDirection: "row",
                                            borderBottomWidth: .8,
                                            borderBottomColor: "#aaa"
                                        }}>
                                        <Icon style={{ alignSelf: "center" }} name="ios-contact" size={60} color="#1567d3" />
                                        <View style={{ flex: 1, padding: 5, flexDirection: "row" }}>
                                            <View style={{ marginLeft: 27 }}>
                                                <Text style={{
                                                    fontSize: 18,
                                                    fontWeight: "800",
                                                    fontFamily: 'Gill Sans',
                                                    color: '#000',
                                                }}>
                                                    {item.providerName}
                                                </Text>
                                                <Text style={{
                                                    fontSize: 18,
                                                    fontWeight: "800",
                                                    fontFamily: 'Gill Sans',
                                                    color: '#000',
                                                }}>
                                                    {item.providerService}

                                                </Text>
                                            </View>
                                            <View style={{ alignItems: "flex-end", justifyContent: "center", flex: 1 }}>
                                                <Icon style={{ marginRight: 20 }}
                                                    name={`ios-heart${fav ? "" : "-empty"}`}
                                                    size={35} color="#f00"
                                                    onPress={() => {
                                                        const currentUser = firebase.auth().currentUser.uid;
                                                        firebase.database().ref(`favorites/${currentUser}/${item.ProviderId}`).remove().then(() => alert("Removed"))
                                                    }}
                                                />
                                            </View>

                                        </View>

                                    </View>
                                </TouchableOpacity>
                            </ScrollView>
                        )
                    }
                    }
                    keyExtractor={(item, index) => index.toString()}
                />
            </View>
        );
    }
}

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

export default UserFavorites;

1 Ответ

1 голос
/ 15 июня 2019

Вы удаляете элемент из базы данных, но не из источника данных плоского списка this.state.favorites, добавьте функцию, которую вы будете вызывать после удаления элемента из базы.

_onRemove = (_item) => { 

   this.setState({ 
     favorites: this.state.favorites.filter(item => item.ProviderId !== _item.ProviderId) 
   });
}

Передайте нужный элементчтобы удалить функцию в вашем плоском списке

renderItem={({ item }) => {
  return ....
   //scrollview code
   <Icon style={{ marginRight: 20 }}
    name={`ios-heart${fav ? "" : "-empty"}`}
    size={35} color="#f00"
    onPress={() => {
       const currentUser = firebase.auth().currentUser.uid;
       ....
       // firebase code
       this._onRemove(item);
    }
   />
  ....
  //rest of the code
}}
...