react-native - 来自 React Native 中 Firebase Firestore 的重复数据
问题描述
我正在尝试从 Firestore 中的数据库加载一些数据,但我不明白为什么该变量会从中加载重复的文档。
在 Firestore 中,我有一个包含两个元素 test1 和 test2 的集合,如下面的屏幕截图所示。
我正在我的函数 seleccionarTest() 中加载完整的集合,并且我想加载带有两个文档(test1 和 test2)的 var 测试,我稍后将在 Touchable Flat List 中使用它们。
见功能:
export default function AsignarTest({route, navigation}){
console.log("Entrando en asignar test");
const {usuario} = route.params;
const [animacion, setAnimacion] = useState(true);
const [tests, setTests] = useState([]);
const db = firestore();
function seleccionarTests(){
db.collection("test").get()
.then((querySnapshot) =>{
var i=0;
querySnapshot.forEach((documentSnapshot)=>{
tests.push({id:documentSnapshot.id, datos: documentSnapshot.data()});
});
setAnimacion(false);
console.log(tests);
return;
}).catch((error)=>{
console.log(error);
});
}
//Gestionamos cuando el usuario selecciona una peluqueria
const gestionarClick = (id)=>{
//Todo
console.log(id);
}
const p = seleccionarTests();
return(
<View style={estiloGlobal.container}>
<ActivityIndicator
size="small"
color = "#dd85be"
animating = {animacion} />
<View>
<FlatList
keyExtractor = {(item) => item.id}
data={tests}
renderItem= {({item})=> (
<TouchableOpacity
onPress={() =>{gestionarClick(item.id)}}>
<View style={estiloGlobal.lineaRecta}>
<View style={{paddingLeft: 10}}>
<Text style= {estiloGlobal.botonTexto}>{item.id}</Text>
</View>
</View>
</TouchableOpacity>
)} />
</View>
</View>
);
}
不幸的是,正如您在下一个屏幕截图中看到的那样,我在 console.log 中的 var 有 4 个文档(test1、test2、test1、test2),我不明白为什么这些文档会重复。
感谢您的意见!
解决方案
The reason why this is happening is either because somewhere else in your code the seleccionarTests
function is being invoked a second time or that this data was actually junk data from a previous execution that was never cleaned in the array.
Either way in order to fix that you need to clear your array everytime you execute the function, doing something like this:
function seleccionarTests(){
this.setState({tests: []});
db.collection("test").get().then((querySnapshot) =>{
var i=0;
querySnapshot.forEach((documentSnapshot)=>{
tests.push({id:documentSnapshot.id, datos: documentSnapshot.data()});
});
setAnimacion(false);
console.log(tests);
return;
}).catch((error)=>{
console.log(error);
});
}
NOTE: This should be always done as a best practice in a case like yours where you are populating an array with all the results of your collection to prevent duplicate data.
推荐阅读
- javascript - 通过 JavaScript 切换锚点和图像元素的属性
- computer-science - L={⟨M⟩|的前缀是什么?M 是接受其字母表上所有回文的 TM?
- php - isset 中的非法偏移类型或空(Laravel 7)
- ssas - 表格模型中 SSAS 计算成员的等效项
- java - Java中的旋转文本
- javafx - JavaFX - 设置 TableView 标题的样式
- arrays - 将段落(字符串)存储到将用于迭代的数组中 - word vba
- r - 为什么 R 包 Googlesheets4 无法识别我的凭据...?
- r - 将 metafor::rma 与 geom_smooth 一起使用?
- html - 在平行四边形内水平居中对象