简体   繁体   English

未定义不是对象React Native和Firebase

[英]Undefined is not an object React Native and Firebase

I'm building a React-Native app using CRNA (Node: v9.3.0, npm: 4.6.1, RN: 0.50.4 React: 16.0.0). 我正在使用CRNA构建一个React-Native应用程序(Node:v9.3.0,npm:4.6.1,RN:0.50.4 React:16.0.0)。

My console give mi the following error: "undefined is not an object (evaluating 'secciones.forEach')" 我的控制台给了mi以下错误:“未定义不是对象(正在评估'secciones.forEach')”

The code that have the bug is the following: 包含该错误的代码如下:

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);
    }
}

I'm calling the buscarProfesores function is this snippet: 我正在调用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);
    }
}

I think I can identify some of the problems in the code, 我想我可以找出代码中的一些问题,

buscarProfesores : 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
}

Therefore, you should re-write your buscarProfesores function. 因此,您应该重新编写buscarProfesores函数。 You got it almost perfect in buscarSecciones() function, just write this function in the same fashion and you're on the right track. buscarSecciones()函数中,它几乎是完美的,只需以相同的方式编写此函数,您就可以走上正确的轨道。 However, what's different is that you are fetching many things from the database and putting them in an array in this function, you need a little help of Promise.all() here: 但是,不同的是,您正在从数据库中获取许多内容,并将它们放入此函数的数组中,您需要在此处提供一些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() takes an array of promises and execute them, only when all of the promises are successfully executed will the .then() be executed later, otherwise the .catch() will be executed Promise.all()取承诺的数组,并执行它们,只有当所有承诺都成功执行将在.then()以后执行,否则.catch()将被执行

There's not much problem with buscarSecciones() function, simply change .on to .once , and delete return false statement buscarSecciones()函数buscarSecciones()问题,只需将.on更改为.once ,然后删除return false语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM