Cloud Firestore错误:函数Query.startAfter()需要有效的第一个参数,但未定义

时间:2019-05-08 07:48:58

标签: javascript firebase react-native google-cloud-firestore

我正在使用Cloud Firestore实现Infinite Scroll,并使用lastVisible作为文档参考,以了解在何处是另外5个用户的刷新查询(限制设置为5)。

问题来自“ lastVisible”,并且在行中以未定义状态返回。当运行初始的“ retrieveUsers”功能时,会将lastVisible添加到visibles数组中,但不会在restoreMore函数中。

console.log(this.state.visibles)

Visibles (Retrieve More)
Array [
  Object {
    "company": "Google",
    "first_name": "Dan",
    "last_name": "Jones",
    "email": null,
    "phone_number": "(553) 402-8023",
  },
  undefined,
]
Paginated Query starting (Retrieve More)

问题在于在this.state.visibles数组中添加了第二个,第三个,第四个等可见文件。它是未定义的,由于它不知道最后一个可见文档是什么,因此引发了我的Cloud Firestore查询。

错误是:“函数Query.startAfter()需要有效的第一个参数,但未定义。”

// Imports: Dependencies
import React, { Component } from "react";
import { ActivityIndicator, Dimensions, FlatList, View, SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity } from 'react-native';
import * as firebase from 'firebase';
import 'firebase/firestore';
import firebaseConfig from '../config/config';

// Imports: Components
import UserSelector from '../components/UserSelector';
import TitleLarge from '../components/TitleLarge';

// Screen Dimensions
const { height, width } = Dimensions.get('window');

// Screen: Flat List (Users)
class FlatListUsers extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      limit: 5,
      visibles: [],

      loading: false,
      refreshing: false,
    };
  }

  // Component Will Mount
  componentWillMount = () => {
    // Firebase: Initialize
    firebase.initializeApp({
      apiKey: `${firebaseConfig.apiKey}`,
      authDomain: `${firebaseConfig.authDomain}`,
      databaseURL: `${firebaseConfig.databaseURL}`,
      projectId: `${firebaseConfig.projectId}`,
      storageBucket: `${firebaseConfig.storageBucket}`,
      messagingSenderId: `${firebaseConfig.messagingSenderId}`,
    });
  }

  // Component Did Mount
  componentDidMount = () => {
    this.retrieveUsers();
  }

  // Retrieve Users
  retrieveUsers = async () => {
    try {
      // Set State: Loading
      this.setState({ loading: true });

      // Firebase: Database + Settings
      const db = firebase.firestore();

      // Query
      console.log('Fetching Users')
      let initialQuery = await db.collection('licenses')
                            .where('company', '==', 'Google')
                            .orderBy('first_name')
                            .limit(5)

      // Query Snapshot
      let documentSnapshots = await initialQuery.get();

      // Document Data
      let documentData = documentSnapshots.docs.map(document => document.data());

      // Last Visible Document (To Start From For Proceeding Queries)
      let lastVisible = documentData[documentData.length - 1];

      // Set State
      this.setState({
        data: [...this.state.data, ...documentData],
        visibles: [...this.state.visibles, lastVisible],
        loading: false,
        refreshing: false,
      });

      console.log('Last Visible');
      console.log(this.state.visibles);
    }
    catch (error) {
      console.log(error);
    }
  };

  // Retrieve More Users
  retrieveMore = async () => {
    try {
      console.log('Retrieving more Users (Retrieve More)');
      this.setState({ loading: true });
      console.log('Visibles (Retrieve More)');
      console.log(this.state.visibles);

      // Firebase: Database + Settings
      const db = firebase.firestore();

      // Query
      console.log('Paginated Query starting (Retrieve More)');
      let initialQuery = await db.collection('licenses')
                            .where('company', '==', 'Google')
                            .orderBy('first_name')
                        .startAfter(this.state.visibles[this.state.visibles.length - 1])
                        .limit(5);

      // Query Snapshot
      let documentSnapshots = await initialQuery.get();

      // Last Visible Document (To Start From For Proceeding Queries)
      let lastVisible = documentSnapshots[documentSnapshots.length - 1];
      console.log('Last Visible');
      console.log(typeof this.state.lastVisible);
      console.log(JSON.stringify(this.state.lastVisible));

      // Document Data
      let documentData = documentSnapshots.docs.map(document => document.data());

      // Set State
      this.setState({
        data: [...this.state.data, ...documentData],
        visibles: [...this.state.visibles, lastVisible],
        loading: false,
        refreshing: false,
      });
    }
    catch (error) {
      console.log(error);
    }
  };

  // Render Header
  renderHeader = () => {
    try {
      return (
        <View style={styles.activityIndicator}>
          <TitleLarge title="Users" />
        </View>
      )
    }
    catch (error) {
      console.log(error);
    }
  };

  // Render Footer
  renderFooter = () => {
    try {
      // Check If Loading
      if (this.state.loading) {
        return <ActivityIndicator />
      }
      else {
        return null;
      }
    }
    catch (error) {
      console.log(error);
    }
  };

  render() {
    return (
      <SafeAreaView style={styles.container}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => ( 
            <UserSelector
              firstName={item.first_name}
              lastName={item.last_name}
              company={item.company}
            />
          )}
          keyExtractor={(item, index) => String(index)}
          ListHeaderComponent={this.renderHeader}
          ListFooterComponent={this.renderFooter}
          onEndReached={()=> {
            if (this.state.loading === false) {
              this.retrieveMore();
            }
          }}          
          onEndReachedThreshold={0}
        />
      </SafeAreaView>
    )
  }
}

// Styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    height: height,
    width: width,
    borderTopWidth: 0,
    borderBottomWidth: 0,
  },
  scrollView:{
    height: 'auto',
  },
  userContainer: {
    width: width,
    marginBottom: 7,
  },
  itemText: {
    fontFamily: 'System',
    fontSize: 17,
    fontWeight: '400',
    color: '#222222',
    marginLeft: 16,
  },
  activityIndicator: {
    paddingVertical: 20,
    borderTopWidth: 0,
    borderTopColor: '#CED0CE',
  },
});

// Exports
export default FlatListUsers

0 个答案:

没有答案