如何在 FlatList ReactNative/React 中显示状态? [英] How to display state in FlatList ReactNative/React?
问题描述
我的 React Native 应用中有记录状态.
I have record state in my react native app.
state{
record:[] //some data inside, When i console my state it looks like this:
}
我的记录状态的控制台输出:
Console output of my record state:
Array [
Object {
"name": "abc",
"age": 23,
},
]
Array[
Object {
"name": "xyz",
"age": 27,
},
]
当我通过 FlatList 渲染它时,它只显示名为 abc 和年龄 23 的数组的第一项.同时它还应该加载 2 个处于状态的数组项,即名称 xyz 和年龄 27.下面是输出的代码状态.
When i render it through FlatList it shows only first item of array that is name abc and age 23. While it should also load 2 array item in state, which is name xyz and age 27. below is the code for output of state.
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>
);
}
我想在我的屏幕上加载完整的状态.
I want to load complete state on my screen.
推荐答案
发生这种情况是因为在 this.state.record 中有 2 个不同的数组.尝试将您的数据数组分散在 state 内或将它们组合成 1 个联合数组.你的 this.state.record 应该是这样的
It happens because you have 2 different arrays inside this.state.record. Try to spread your data arrays inside state or combine them into 1 union array. Your this.state.record should look like this
state = {
records: [
{ name: 'xyz', age: '23', },
{ name: 'abc', age: '27', },
]
这将显示包含 2 个对象的列表
This will show you list with 2 objects
console.log('STATE RECORDS', this.state.records)
// console.log output
STATE RECORDS [
{ name: 'xyz', age: '23', },
{ name: 'abc', age: '27', },
]
这篇关于如何在 FlatList ReactNative/React 中显示状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!