小程序

在微信小程序中使用解构赋值实现上拉刷新

2023-01-06


在微信小程序中使用解构赋值实现上拉刷新 


解构赋值语法是一种 Javascript 表达式。通过解构赋值, 可以将属性/值从对象/数组中取出,赋值给其他变量。


let a, b, rest;

[a, b] = [10, 20];


console.log(a);

// expected output: 10


console.log(b);

// expected output: 20


[a, b, ...rest] = [10, 20, 30, 40, 50];


console.log(rest);

// expected output: Array [30,40,50]


let a = [10,20];

let b = [20,30];

let c;


c = [...a, ...b];

console.log(c);

//> Array [10, 20, 20, 30]



在微信小程序中实现上拉加载更多数据主要通过生命周期函数onReachButtom()

// 加载下一页数据

    onReachBottom: function(){

        // console.log("滑动触底");

        console.log(this.data.sector)

        let next = this.data.next;

        this.fetchStudents(this.data.majorId, ++next, this.data.sector);

        this.setData({

            next: next

        })

    },


    fetchStudents(majorId, next, sector) {

        request({

            url: "/api/data/contacts_students",

            data: {

                stuMajor: majorId,

                stuSector: sector,

                page: next

            }

        })

        .then(result => {

            this.setData({

                students: [...this.data.students, ...result.data.students]

            })

        })

    },

[...this.data.students, ...result.data.students] 就表示将获取的数据 result.data.students 和this.data.students 解析出来,组成一个新的数组赋值给students



解构赋值除了可以对数组进行解构赋值,还可以对对象进行解构赋值

var o = {p: 42, q: true};

var {p, q} = o;


console.log(p); // 42

console.log(q); // true



传统对数组进行追加元素会采用array.push

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.push("Kiwi")

不过采用这种方式对数组进行数据追加的一个缺点是,如果需要追加的数据量比较多,需要进行遍历才能进行添加完成