📜  分页反应猫鼬 - Javascript代码示例

📅  最后修改于: 2022-03-11 15:04:12.033000             🧑  作者: Mango

代码示例1
//server

// An example of a controller function for Express.js
async getAllUser (req, res) {
    try {
      const limit = parseInt(req.query.limit); // Make sure to parse the limit to number
      const skip = parseInt(req.query.skip);// Make sure to parse the skip to number

      // We are using the '3 layer' architecture explored on the 'bulletproof node.js architecture'
      // Basically, it's just a class where we have our business logic
      const userService = new userService();
      const users = await userService.getAll(limit, skip);

      return res.status(200).json(users);
    } catch(e){
      return res.status(500).json(e)
    }
},

class UserPaginationExample {
    getAll(limit = 0, skip = 0) {
        return UsersModel.aggregate([
            { $match: {} },    // This is your query
            { $skip: skip },   // Always apply 'skip' before 'limit'
            { $limit: limit }, // This is your 'page size'
        ])  
    }
}



//client

import React, { useState, useEffect } from 'react'

const fetchUsers = (limit, skip) => {
    // Make sure you send 'limit' and 'skip' as query parameters to your node.js server
    fetch(`/api/users?limit=${limit}&skip=${skip}`) 
        .then((res) => {
            this.setState({
                users: res.data;
            })
        })
}

const userList = () => {

    const [users, setUsers] = useState([]);
    const [limit, setLimit] = useState(20);
    const [skip, setSkip] = useState(0);

    const nextPage = () => {
        setSkip(skip + limit)
    }

    const previousPage = () => {
        setSkip(skip - limit)
    }

    useEffect(() => {
        fetchUsers(limit, skip)
    }, [skip, limit])


    return (
{ users.map(user =>
{ user.name } { user.email } { user.lastLogin }
) }
Previous Page
Next Page
) }