【发布时间】:2020-06-11 12:30:36
【问题描述】:
我正在尝试通过构建自己的小应用程序来学习 React Native。我可以添加和编辑添加到主屏幕的项目。问题是列表不会自动更新,而是必须由用户刷新。这导致他们可能没有注意到他们所做的更改,或者他们想知道新项目在哪里。
这是我目前用于主屏幕的代码。它检索用户的所有对象并将它们添加到平面列表中。
componentDidMount = () => {
this.loadFeed(this.state.userId);
}
addToFlatList = (food_feed, data, food) => {
const that = this;
const foodObj = data[food];
database.ref('users').child(this.state.userId).child('username').once('value').then(function(snapshot) {
const exists = (snapshot.val() !== null);
if (exists) {
food_feed.push({
id: food,
amount: foodObj.amount,
bestBefore: foodObj.bestBeforeDate,
description: foodObj.description,
name: foodObj.name,
useBy: foodObj.useByDate
});
that.setState({
refresh: false
});
}
}).catch(error => console.log(error));
}
loadFeed = (userId) => {
this.setState({
refresh: true,
food_feed: []
});
const that = this;
const loadRef = database.ref('users').child(userId).child('foods');
loadRef.once('value').then(function(snapshot) {
const exists = (snapshot.val() !== null);
if (exists) {
let data = snapshot.val();
const food_feed = that.state.food_feed;
that.setState({
empty: false
});
for (const food in data) {
that.addToFlatList(food_feed, data, food);
}
} else {
that.setState({
empty: true,
refresh: false
});
}
}).catch(error => console.log(error));
}
我已经进行了几次搜索,但似乎无法获得我想要的结果。
【问题讨论】:
标签: reactjs react-native firebase-realtime-database