【问题标题】:How to display state in FlatList ReactNative/React?如何在 FlatList ReactNative/React 中显示状态?
【发布时间】:2021-03-13 10:49:20
【问题描述】:

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

state{
    record:[] //some data inside, When i console my state it looks like this:
}

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

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

当我通过 FlatList 渲染它时,它只显示名称为 abc 和年龄 23 的数组的第一项。虽然它还应该在状态下加载 2 个数组项,即名称 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>
    );

 }

我想在我的屏幕上加载完整的状态。

【问题讨论】:

  • 您的状态是否包含数组数组?
  • 我想是的,请检查我的代码,我已经添加了一些代码。

标签: javascript reactjs react-native


【解决方案1】:

这是因为 this.state.record 中有 2 个不同的数组。 尝试将您的数据数组分布在状态内或将它们组合成 1 个联合数组。你的 this.state.record 应该是这样的

state = {
  records: [
    { name: 'xyz', age: '23', },
    { name: 'abc', age: '27', },
  ]

这将显示包含 2 个对象的列表

console.log('STATE RECORDS', this.state.records)

// console.log output
STATE RECORDS [
  { name: 'xyz', age: '23', },
  { name: 'abc', age: '27', },
]

【讨论】:

  • 嗨。请检查我是否添加了更多代码并指导我如何执行此操作。
  • 如何在 displaydata() 中执行此操作?请指导
  • 感觉就像你在传播包含数组的文档。您需要在从 doc.data() 传播的 doc 中再次映射数组属性,这应该是 this.setState({ ...urecords.${name_of_your_array_property} })
  • 是的,如何克服这个问题?我是新手请指导
  • 你的意思是 this.setState({ record : [...urecords.${name,age}] }) .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 2022-01-22
相关资源
最近更新 更多