【问题标题】:How to load complete state in FlatList Component?如何在 FlatList 组件中加载完整状态?
【发布时间】:2021-06-11 09:32:12
【问题描述】:

我的 react native 应用中有记录状态。

state{
    record:[],
    //initially empty, then i setState in displaydata(), then state looks like this in console 
}

我的记录状态的控制台输出:

Array [
  Object {
    "name": "abc",
    "age": 23,
    },
]
Array[
 Object {
    "name": "xyz",
    "age": 27,
    },
]

下面是 displaydata 函数,当通过 FlatList 渲染它时,它只显示数组的第一项,即名称 abc 和年龄 23。虽然它还应该加载状态中的第二个数组项,即名称 xyz 和年龄 27。下面是状态输出代码。

displaydata(){
        firebase.firestore()
            .collection('users').where('age', '>=', 21)
            .get()
            .then(querySnapshot => {

                querySnapshot.forEach(documentSnapshot => {
                    const urecords = [];
                    const udata = documentSnapshot.data();
                    urecords.push(udata);
                   
                    this.setState({ record: [...urecords] })

                });
            });
    }
}
render(){
    return(
    <View style={{ flex: 1 }}>
    {this.state.record ? (
    <>
    <Text>Data from firebase firestore</Text>
          <FlatList
                 style={{ flex: 1 }}
                 data={this.state.record}
                 keyExtractor={(key, index) => key + index}
                 renderItem={(itemData) => {

                     console.log(this.state.record); // it displays all data of state in console as i have consoled above
                     return <Text>{itemData.item.name}{itemData.item.age}</Text>; // it displays first array data(item) only, which is abc and 23

                  }
               }
          />
    </>
       ) : (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
         <ActivityIndicator size="large" color="black" />
      </View>
     )}
    </View>
    );

 }

我想像在控制台中一样在屏幕上加载完整状态。 TIA

【问题讨论】:

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


    【解决方案1】:

    你在这里覆盖你的状态:

    this.setState({ record: [...urecords] })

    改为执行以下操作:

    this.setState({ record: [...this.state.record,...urecords]})

    首先我们复制以前的条目,然后添加新条目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      相关资源
      最近更新 更多