如果数据更新,如何更新 FlatList
How to update FlatList if data is updated
我获取数据的方式是在 componentWillMount 方法中,它在应用程序启动时呈现 FlatList 时工作正常,但是当我添加数据时,我只想更新我的 flatList。我该怎么做 这是代码片段:
componentWillMount() {
console.log(`componentDidUpdate`, prevProps);
const user = firebase.auth().currentUser;
if (user != null) {
const db = firebase.firestore();
const docRef = db.collection('userCheckInHistory').doc(user.uid);
docRef
.get()
.then(doc => {
if (doc.exists) {
let shopId = this.props.shopId;
let userShopHistoryData = doc.data();
let userShopPick = userShopHistoryData[shopId];
this.setState({
checkInHistory: userShopPick,
shopId: this.props.shopId
});
} else {
console.log('No such document!');
return false;
}
})
.catch(function(error) {
console.log('Error getting document:', error);
});
}
}
现在这是我的 FlatList 代码:
renderHistoryList() {
const sortedData = Common.getArrayByObject(this.state.checkInHistory);
if (this.state.checkInHistory !== '') {
return (
<FlatList
data={sortedData}
extraData={this.state}
keyExtractor={this._keyExtractor}
renderItem={({ item }) => (
<MyListItem
id={item}
onPressItem={this._onPressItem}
selected={!!this.state.selected.get(item)}
title={item}
/>
)}
/>
);
} else {
return <Spinner />;
}
}
当您从 api 获取数据时,使用该数据设置您的状态。然后,如果您添加数据和 setState,React Native 将重新渲染应用程序,您将在列表中看到您的数据。
我获取数据的方式是在 componentWillMount 方法中,它在应用程序启动时呈现 FlatList 时工作正常,但是当我添加数据时,我只想更新我的 flatList。我该怎么做 这是代码片段:
componentWillMount() {
console.log(`componentDidUpdate`, prevProps);
const user = firebase.auth().currentUser;
if (user != null) {
const db = firebase.firestore();
const docRef = db.collection('userCheckInHistory').doc(user.uid);
docRef
.get()
.then(doc => {
if (doc.exists) {
let shopId = this.props.shopId;
let userShopHistoryData = doc.data();
let userShopPick = userShopHistoryData[shopId];
this.setState({
checkInHistory: userShopPick,
shopId: this.props.shopId
});
} else {
console.log('No such document!');
return false;
}
})
.catch(function(error) {
console.log('Error getting document:', error);
});
}
}
现在这是我的 FlatList 代码:
renderHistoryList() {
const sortedData = Common.getArrayByObject(this.state.checkInHistory);
if (this.state.checkInHistory !== '') {
return (
<FlatList
data={sortedData}
extraData={this.state}
keyExtractor={this._keyExtractor}
renderItem={({ item }) => (
<MyListItem
id={item}
onPressItem={this._onPressItem}
selected={!!this.state.selected.get(item)}
title={item}
/>
)}
/>
);
} else {
return <Spinner />;
}
}
当您从 api 获取数据时,使用该数据设置您的状态。然后,如果您添加数据和 setState,React Native 将重新渲染应用程序,您将在列表中看到您的数据。