gpt4 book ai didi

javascript - 使用 React Native 的 Firebase 查询未显示在我的屏幕上(但显示在 console.log 上)

转载 作者:行者123 更新时间:2023-11-30 19:59:49 26 4
gpt4 key购买 nike

我的数据按预期显示在 console.log 上,但没有显示在我的屏幕上。这是控制台日志的屏幕截图。

enter image description here

这是我的代码:

componentWillMount = () => {
this.getData();
}

getData(){
const { currentUser } = firebase.auth();
firebase
.database()
.ref(`/users/${currentUser.uid}/data/`)
.orderByKey()
.on('child_added', snap => {

//Is this correct or does it need to be formatted a different way?
snap.key,
snap.val().Weight

//note that the console logs below displays the data
console.log(snap.key)
console.log(snap.val().Weight)

})
}

renderRow = () => {
return (
<View style={[styles.card, styles.cardBorderTop]}>
<Text>
{snap.key} //Is this the correct way to reference this value?
</Text>
<Text style={[styles.textRight]}>
{snap.val().Weight} //Is this the correct way to reference this value?
</Text>
</View>
)
}

render() {
return (
<View style={[styles.container]}>
<FlatList
data={this.getData} //Is this the correct data reference?
renderItem={this.renderRow}
/>
</View>
);
}
}

这是我的屏幕渲染方式。请注意,我希望数据呈现在 FlatList 上。 enter image description here

任何帮助将不胜感激。

附带说明一下,我现在意识到我需要将日期存储为 ISO-8601,以便可以对它们进行正确排序,我将在弄清楚如何获取查询数据以呈现在我的屏幕。

更新我意识到我的问题没有我预想的那么清楚,对此我深表歉意。我需要的是能够通过date keyWeight child 查询我的数据。我能够在控制台上使用 snap.key 和 snap.val().Weight 成功地做到这一点,但是它看起来不像是在我的 FlatList 上显示数据所需的正确引用,而这正是我需要帮助的.

作为引用,这是我的 Firebase 数据库: enter image description here

最佳答案

您的 getData 函数目前不返回任何内容,因此虽然 View 可能会调用 getData(),但它什么也得不到。

但是简单地添加一个return 语句并没有帮助,因为数据是异步加载的。在 React 中,您应该将数据放在组件的状态中(通过调用 setState()),然后在渲染器中使用它。

在代码中:

componentWillMount = () => {
this.setState({ data: [] });
this.getData();
}

getData(){
const { currentUser } = firebase.auth();
firebase
.database()
.ref(`/users/${currentUser.uid}/data/`)
.orderByKey()
.on('child_added', snap => {
var data = this.state.data;
data.push({ key: snap.key, weight: snap.val().Weight });
this.setState({ data: data });
})
}

所以这样:

  • 将状态中的 data 属性初始化为空数组。
  • 将每个新项目添加到 data,因为它来自数据库。

有了这个,你可以渲染数据数组:

renderRow = ({item}) => {
return (
<View style={[styles.card, styles.cardBorderTop]}>
<Text>
{item.key}
</Text>
<Text style={[styles.textRight]}>
{item.Weight}
</Text>
</View>
)
}

render() {
return (
<View style={[styles.container]}>
<FlatList
data={this.state.data}
renderItem={this.renderRow}
/>
</View>
);
}

这最后一点可能包含语法错误,因为我从未使用过 FlatList。如有疑问,请与后者的文档进行比较 here .

关于javascript - 使用 React Native 的 Firebase 查询未显示在我的屏幕上(但显示在 console.log 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53511480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com