从Firebase渲染FlatList中的数据 [英] Rendering data in FlatList from firebase
问题描述
我正在使用React Native 0.49.我有从firebase提取的数据,用户列表 users/
,此列表中的每个项目都设置为 firebase.database().ref('users/'+ userId).set(userInfo)
userId是currentUser的 uid
.
I am using React Native 0.49. I have data fetched from firebase, list of users users/
, each item in this list was set like this firebase.database().ref('users/' + userId).set(userInfo)
userId is the uid
of the currentUser.
现在,我正在取回(在操作中-redux):
Now I am fetching back (in actions - redux):
export function getPeople(){
return (dispatch) => {
dispatch(getPeopleRequest());
getData().then(result => {
dispatch(getPeopleSuccess(result.val()))
})
.catch(error => {
dispatch(getPeopleFailure(error))
});
}
}
const getData = () => {
const userRef = firebase.database().ref('users/').limitToFirst(20);
return userRef.once('value');
}
在组件中,我试图在FlatList中呈现数据,但是它没有呈现任何内容,我不知道自己在做什么错:
In component, I am trying to render the data in FlatList, but it's not rendering anything, I don't know what I'm doing wrong:
componentDidMount(){
this.props.getPeople();
}
_renderItem = ({ item }) => (
<View style={{flex: 1}}>
<Text>{item}</Text>
</View>
);
render(){
const { inProgress, people, error } = this.props.peopleData;
return (
<FlatList
data={people}
renderItem={this._renderItem}
/>
);
}
当控制台记录 people
时,结果如下: {cpycwkz7exVBzmhaLEtHjMW66wn1:{…},UbIITfUANmb63cYE2x7dZRZ0pfK2:{…}}
when console log people
this is result:
{cpycwkz7exVBzmhaLEtHjMW66wn1: {…}, UbIITfUANmb63cYE2x7dZRZ0pfK2: {…}}
推荐答案
FlatList
组件希望其 data
属性是一个数组.您将其作为对象传递.您可以将其更改为对象数组.然后,在您的 _renderItem
方法中, item
也将是一个对象,并且不能立即在< Text>
中进行渲染,从项目对象中提取文本值,然后将其呈现为:< Text> SOME_TEXT_NOT_AN_OBJECT</Text>
FlatList
component expects its data
prop to be an array. You are passing it as an Object. You can change it to an array of Objects. Then too in your _renderItem
method the item
will be an object and it can't be rendered straight away in <Text>
, you have to extract a text value from the item object and than render it as: <Text>SOME_TEXT_NOT_AN_OBJECT</Text>
您可以将people对象转换为数组,然后将其传递给< FlatList
,如下所示:
You can convert your people object to an array and pass it to the <FlatList
like this:
render(){
const { inProgress, people, error } = this.props.peopleData;
let ArrayOfPeopleObject = Object.values(people)
return (
<FlatList
data={ArrayOfPeopleObject}
renderItem={this._renderItem}
/>
);
}
现在, _renderItem
方法中的每个 item
将成为一个对象,您可以从任何键中提取值并将其呈现在< Text> 代码>.
Now each item
in the _renderItem
method will be an object and you can extract value from any key and render it in the <Text>
.
这篇关于从Firebase渲染FlatList中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!