react hook分页示例代码来啦请注意查收
Posted 老张在线敲代码
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react hook分页示例代码来啦请注意查收相关的知识,希望对你有一定的参考价值。
在进行下面的操作前先确认自己的react项目是否创建完善
首先src下面创建unit文件
//index.js
import axios from "axios";
const Unit = {
async getApi(ajaxCfg) {
let data = await axios.get(
ajaxCfg.url,
{ params: ajaxCfg.cfg },
{
headers: ajaxCfg.headers,
}
);
return data;
},
async getApi2(url, cfg, headers) {
let data = await axios.get(
url,
{ params: cfg },
{
headers: headers,
}
);
return data;
},
async postApi(url, cfg, headers) {
let fd = new FormData();
for (let key in cfg) {
fd.append(key, cfg[key]);
}
let data = await axios.post(url, fd, {
headers: headers,
});
return data;
},
async putApi(url, cfg, headers) {
// import qs from 'qs';
// let data = await axios.put(url,qs.stringify(cfg),{
// headers: {
// 'Content-Type':'application/x-www-form-urlencoded',
// }
// })
// return data;
},
async requestApi(cfg, headers, file) {
let fd = new FormData();
fd.append("param", JSON.stringify(cfg));
if (file) {
// 上传证明
if (file.length) {
for (let i = 0, len = file.length; i < len; i++) {
fd.append("files", file[i]);
}
} else {
// 单个上传
for (let key in file) {
fd.append(key, file[key]);
}
}
}
let data = await axios.post("/batch", fd, {
headers: headers,
});
return data;
},
};
export default Unit;
在src下面再次创建一个名为setupProxy.js文件
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
"字段",
createProxyMiddleware({
target: "接口地址",
changeOrigin: true,
})
);
};
最后在index.jsx编写逻辑代码
//index.jsx
import React, { useState, useEffect } from "react";
//引入unit文件
import Unit from "../../unit";
import { Pagination } from "antd";
const App = () => {
const [Data, setData] = useState([]);
const [curr, setCurr] = useState({
current: 1,
total: 10,
});
//设置默认页面跟数据条数
const getData = (page = 1, size = 10) => {
// console.log(page, size);
const ajaxCfg = {
page_number: page,
page_size: size,
};
//接口请求数据
Unit.getApi2("接口字段", ajaxCfg, {}).then((res) => {
if (res.data.code === 200) {
setData([...res.data.data]);
setCurr({ current: page, total: res.data.total });
}
});
};
//页面渲染数据
const lists = () => {
return Data.map((val, index) => {
return <li key={index}>{val.main_title}</li>;
});
};
//加载延迟
useEffect(() => {
setTimeout(() => {
getData();
}, 2000);
}, []);
return (
<div>
{Data.length > 0 ? (
<ul>
{lists()}
<Pagination
defaultCurrent={curr.current}
total={curr.total}
onChange={getData}
/>
</ul>
) : (
<div>正在加载...</div>
)}
</div>
);
};
export default App;
以上是关于react hook分页示例代码来啦请注意查收的主要内容,如果未能解决你的问题,请参考以下文章
React 17 + Vite + ECharts 实现疫情数据可视化「03 学习 React Hooks」