javascript - Undefined 不是一个对象 React Native 和 Firebase

标签 javascript firebase react-native firebase-realtime-database

我正在使用 CRNA 构建 React-Native 应用程序(Node:v9.3.0,npm:4.6.1,RN:0.50.4 React:16.0.0)。

我的控制台给出以下错误: “未定义不是一个对象(评估'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() 接受一个 Promise 数组并执行它们,只有当所有的 Promise 都成功执行时才会稍后执行 .then(),否则 .catch() 将被执行

buscarSecciones()函数没有太大问题,只需将.on改为.once,并删除return false 声明

关于javascript - Undefined 不是一个对象 React Native 和 Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252778/

相关文章:

javascript - JavaScript 中字母数字字符串末尾的递增数字

javascript - 类型错误 : migrationCreator is not a function

javascript - Highcharts 删除第一个条之前和最后一个之后的空格

ios - 无法在 xcode 中构建我的新 react-native 项目 - 获取配置文件配置错误

javascript - 改进了在 javascript 中构建嵌套唯一值数组的方法

firebase - CLI 安装不工作(缺少 google_app_id)

java - 在 Firebase 监听器中设置 Singleton 属性值

ios - 如何在 Firebase 中更新新项目

android - 使用 expo build 读取 ECONNRESET

android - React-Native:FlatList 中的反向 zIndex