[英]Undefined is not an object React Native and Firebase
我正在使用CRNA构建一个React-Native应用程序(Node:v9.3.0,npm:4.6.1,RN:0.50.4 React:16.0.0)。
我的控制台给了mi以下错误:“未定义不是对象(正在评估'secciones.forEach')”
包含该错误的代码如下:
async buscarProfesores(secciones) {
const profesores = [];
secciones.forEach(seccion => {
firebase.database().ref(`/Usuarios/${seccion.profesor}`).on('value', async snapshot => {
const prof = snapshot.val();
await profesores.push(prof.nombre);
});
});
return await profesores;}
async buscarSecciones() {
try {
const usuario = firebase.auth().currentUser.uid;
let secciones;
await firebase.database().ref(`/Usuarios/${usuario}`)
.on('value', snapshot => {
secciones = snapshot.val().secciones;
return false;
});
return secciones;
} catch (error) {
console.log(error);
}
}
我正在调用buscarProfesores函数是以下片段:
async auxiliar() {
try {
const secciones = await this.buscarSecciones();
const profesores = await this.buscarProfesores(secciones);
const data = await this.armarSnapshot(secciones, profesores);
return data;
} catch (error) {
console.log(error);
}
}
我想我可以找出代码中的一些问题,
buscarProfesores
:
async buscarProfesores(secciones) {
let profesores = []; // Not 'const', because 'profesores' is not read-only
secciones.forEach((seccion) => {
firebase.database().ref(`/Usuarios/${seccion.profesor}`).once('value', (snapshot) => {
profesores.push(snapshot.val().nombre);
// It shouldn't be 'async (snapshot) => { ... }', because
// What you're doing here is not an async operation, you're simply
// pushing something into an array. If anything is async, it's this:
//
// secciones.forEach(async (seccion) => { firebase.database()... });
});
});
// await return profesores
// Again, there shouldn't be 'await' here, and even if there isn't await here,
// all you'll get is an empty array, because 'firebase.database()...' is an
// async operation, it will be executed, but it will take some amount of time,
// and meanwhile, the rest of the function will be executed at the same time,
// meaning that, the return statement will be executed immediately, therefore,
// you have an empty array
}
因此,您应该重新编写buscarProfesores
函数。 在buscarSecciones()
函数中,它几乎是完美的,只需以相同的方式编写此函数,您就可以走上正确的轨道。 但是,不同的是,您正在从数据库中获取许多内容,并将它们放入此函数的数组中,您需要在此处提供一些Promise.all()
帮助:
async buscarProfesores(secciones) {
let promises = [];
secciones.forEach((seccion) => {
promises.push(firebase.database().ref(`/Usuarios/${seccion.profesor}`).once('value'));
});
await Promise.all(promises)
.then((results) => {
let profesores = [];
results.forEach((result) => {
profesores.push(result.val().nombre);
});
return profesores;
})
.catch((error) => {
console.log(error);
return [];
});
}
Promise.all()
取承诺的数组,并执行它们,只有当所有承诺都成功执行将在.then()
以后执行,否则.catch()
将被执行
buscarSecciones()
函数buscarSecciones()
问题,只需将.on
更改为.once
,然后删除return false
语句
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.