我正在使用 React Native 和 firebase(没有 Redux 或类似的东西)。 我有一个 FlatList 通过使用“on”方法监听 firebase 的变化。 FlatList 监听更改,但是当渲染新数据时,它也会渲染新数据和旧数据。所以我有旧数据,然后是附加了新数据的旧数据。
我像这样检索数据:
firebase.database().ref(`/thisThat/${uid}/arguments/this/`).orderByChild('timestamp')
.on('value', (snapshot) => {
snapshot.forEach((child) => {
thisArr.push(child.val());
});
this.setState({ thisArguments: thisArr });
});
我这样做是因为我希望它被订购(来源:https://stackoverflow.com/a/33897213/5075510)
我的 FlatList 看起来像这样:
<FlatList
data={this.state.thisArguments}
renderItem={this.renderItem}
keyExtractor={(item, index) => index}
ListEmptyComponent={this.emptyList}
extraData={this.state}
/>
我认为这可能与我检索数据的方式有关。当我在没有 forEach 的情况下执行此操作时,一切正常,但不会按顺序呈现。 预先感谢您的帮助!
最佳答案
在将新项目推送到其中之前,您需要清除 thisArr
firebase.database().ref(`/thisThat/${uid}/arguments/this/`).orderByChild('timestamp')
.on('value', (snapshot) =>
{
thisArr = []; // <----- here is the fix
snapshot.forEach((child) =>
{
thisArr.push(child.val());
});
this.setState({ thisArguments: thisArr });
});
关于javascript - 使用 extraData 时,React Native FlatList 会渲染数据两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48503171/