无法在vuex操作Vue.js中对对象数组进行排序

问题描述

我正在尝试对数组进行排序,但是某种程度上,排序控制台并没有证明仅在运行排序。我不明白为什么它没有运行。如果我在简单的javascript中运行相同的代码,则运行良好。如果有人知道发生了什么,那将是一个很大的帮助。

fetchContacts({
    commit
},userId) {
    let contactsArr = [];
    console.log('contact action triggered');
    db.collection("users").doc(userId).collection("contacts").onSnapshot((snapshot) => {
        snapshot.forEach((el) => {
            contactsArr.push({
                name: el.data().name,phone: el.data().phone,email: el.data().email,id: el.id
            });
        })
    })
    console.log('contact array: '+ contactsArr);
    console.log(contactsArr);
    contactsArr.sort((a,b) => {
        console.log('sorting in ');
        const n1 = a.name.toLowerCase();
        console.log(n1);
        const n2 = b.name.toLowerCase();
        console.log(n2);
        if (n1 > n2) {
            return 1;
        } else if (n2 > n1) {
            return -1;
        } else {
            return 0;
        }
    });
    commit('setContacts',contactsArr);
},

enter image description here


enter image description here

解决方法

您应该取消onSnapshot回调内部的排序,因为当前代码以异步方式执行:

 let contactsArr = [];
    console.log('contact action triggered');
    db.collection("users").doc(userId).collection("contacts").onSnapshot((snapshot) => {
        snapshot.forEach((el) => {
            contactsArr.push({
                name: el.data().name,phone: el.data().phone,email: el.data().email,id: el.id
            });
        })

      console.log('contact array: '+ contactsArr);
    console.log(contactsArr);
    contactsArr.sort((a,b) => {
        console.log('sorting in ');
        const n1 = a.name.toLowerCase();
        console.log(n1);
        const n2 = b.name.toLowerCase();
        console.log(n2);
        if (n1 > n2) {
            return 1;
        } else if (n2 > n1) {
            return -1;
        } else {
            return 0;
        }
    });
    commit('setContacts',contactsArr);
    })
   

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...