如何在获取单个数据后强制重新提交Flatlist?

时间:2019-08-21 16:24:15

标签: javascript android reactjs react-native react-native-flatlist

当我从服务器获取单个数据并将其设置为状态并传递给数据道具时,我遇到了平面列表问题,我无法在渲染器中看到任何更新“如果要添加一些加载, d没有收到任何数据,我显示“指示器”,所以指示器消失了,我看到黑屏!

仅供参考,当我启用热重装并在IDE中按Save时,我可以在屏幕上看到单个数据!

那么我该如何强迫它显示数据!

代码

import React, { Component } from "react";
import firebase from "react-native-firebase";
import Icon from "react-native-vector-icons/Ionicons";
import _ from "lodash";

import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  Image,
  Dimensions
} from "react-native";
const { width } = Dimensions.get("screen");
class ListChats extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [],
      noChat: true
    };
  }
  _getUsers = () => {
    let currentUser = firebase.auth().currentUser.uid;
    let ref = firebase.database().ref(`Messages/${currentUser}`);
    let usersKeys = [];

    ref.once("value").then(snapshot => {
      snapshot.forEach(childsnap => {
        usersKeys.push(childsnap.key);
      });
      let usernames = [];
      usersKeys.forEach(key => {
        firebase
          .database()
          .ref("users")
          .child(key)
          .once("value")
          .then(usersShot => {
            let username = usersShot.val().username;
            usernames.push({ username: username, key: key });
          });
      });
      this.setState({ users: usernames,noChat: false });
    });
  };
  componentDidMount() {
    this._getUsers();
  }

  render() {
    if (this.state.noChat) {
      console.log("IF", this.state.users);
      return (
        <View style={styles.container}>
          <Image
            style={{
              width,
              height: width * 0.7,
              resizeMode: "contain"
            }}
            source={require("../../assets/empty.gif")}
          />
          <Text style={{ alignSelf: "center" }}>No Chats Found</Text>
        </View>
      );
    } else {
      console.log("Else", this.state.users);
      return (
        <View style={styles.container}>
          <FlatList
            key={Math.random() * 1000}
            extraData={this.state} // I'm already added 
            data={this.state.users}
            contentContainerStyle={{ flexGrow: 1 }}

            renderItem={({ item }) => {
              return (
                <TouchableOpacity
                  onPress={() =>
                    this.props.navigation.navigate("ChatDetails", {
                      Key: item.key,
                      userName: item.username
                    })
                  }
                >
                  <View style={styles.parent}>
                    <Icon name="ios-contact" size={50} color="#4d8dd6" />
                    <View
                      style={{
                        flex: 1,
                        justifyContent: "flex-start",
                        alignItems: "flex-start",
                        marginHorizontal: 25
                      }}
                    >
                      <Text
                        style={{
                          color: "#000",
                          fontSize: 17
                          // marginHorizontal: 25
                          // alignSelf: "stretch"
                        }}
                      >
                        {item.username}
                      </Text>
                      {/* <Text
                        style={{
                          color: "#a1a1a1",
                          marginHorizontal: 35,
                          marginVertical: 5,
                          alignSelf: "stretch"
                        }}
                        numberOfLines={1}
                        lineBreakMode="tail"
                      >
                        {item.lastMssg.text}
                      </Text> */}
                    </View>
                    <Icon name="ios-chatboxes" size={25} color="#d6d6d6" />
                  </View>
                </TouchableOpacity>
              );
            }}
            keyExtractor={(item, index) => index.toString()}
          />
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center"
  },
  parent: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingVertical: 25,
    marginHorizontal: 15,
    borderBottomWidth: 1,
    borderBottomColor: "#eee"
  }
});

export default ListChats;

2 个答案:

答案 0 :(得分:0)

强制重新提交单位列表。只需在状态中添加一个布尔值就可以说“ forceUpdate”,并且每当有项目添加到平面列表数据时,都将切换该布尔值并将其传递给FlatList的额外数据而不是状态。

答案 1 :(得分:0)

您使用了额外的数据道具,但问题是 flatlist 进行了浅层数据比较,因此当用户的长度发生变化时,它不会影响 flatlist,因此将其替换为 this.state.users

extraData={this.state.users}

你可以在文档中看到它说 flatlist 是 PureCompoment 的实现,而 PureComponent 做了一个浅层比较,这就是它没有重新渲染的原因。 https://reactnative.dev/docs/flatlist#extradata