react 使用express實現簡單的分頁接口

前言

本文基於 react (“react”: “^16.13.1”) ,express(“express”: “~4.16.1”,);
有一定的express瞭解,並能寫簡單的接口。

1.定義一個接口

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  let itemArr = [
    { username: 'Keely'},
    { username: '敖丙' },
    { username: '晨曦時夢見兮' },
    { username: '神三元' },
    { username: '冴羽' },
    { username: 'jsonchao' },
    { username: '夜幕降臨耶'},
    { username: '給我點陽光就燦爛' },
    { username: '沉默王二' },
    { username: '_yuanhao' },
    { username: '蘆半山' }
  ];
  // 數據處理
  let data = [];
  let page = req.query.page; // 頁數
  let pageSize = req.query.pageSize; // 條數
  let len = (1000 - pageSize * (page - 1)) < pageSize ? (1000 - pageSize * (page - 1)) : pageSize; // 返回條數
  for (i = 0; i < len; i++) {
    // 隨機返回數組一項
    let n = Math.floor(Math.random() * itemArr.length + 1) - 1;
    itemArr[n].id = (page - 1) * pageSize + (i + 1);
    data.push(itemArr[n]);
  }
  // 模擬延遲返回數據
  setTimeout(() => {
    res.json({
      data
    });
  }, 500);
});

module.exports = router;

2.使用

import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
  componentDidMount() {
    axios.get('/api/users', {
      params: {
        page: 1,
        pageSize: 10
      }
    })
      .then(res => {
        console.log(res);
      })
    // 在3秒鐘後模擬分頁再次被請求
    setTimeout(() => {
      axios.get('/api/users', {
        params: {
          page: 1,
          pageSize: 6
        }
      })
        .then(res => {
          console.log(res);
        })
    }, 3000);
  }
}

export default App;

3.效果
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章