react.js如何创建分页



我正在使用react进行分页。我找到了下面的逻辑。我有几个问题不明白。

  1. 哪里定义了n作为setPageBlocksetCurrentIndex参数
  2. 如何防止pageBlock变为-1
import React, { useState } from "react";
const dump = [
{
id: 0,
title: "dum1",
},
{
id: 1,
title: "dum2",
},
{
id: 2,
title: "dum3",
},
{
id: 3,
title: "dum4",
},
{
id: 4,
title: "dum5",
},
{
id: 5,
title: "dum6",
},
{
id: 6,
title: "dum7",
},
{
id: 7,
title: "dum8",
},
{
id: 8,
title: "dum9",
},
];
export default function PaginationContainer() {
const [currentIndex, setCurrentIndex] = useState(0);
const [pageBlock, setPageBlock] = useState(0);
let firstPage = pageBlock * 4;
let pages = dump.slice(firstPage, firstPage + 4);
const onClickPageItem = (id) => {
setCurrentIndex(id);
};
const onClickPage = (type) => {
if (type === "prev") {
if (currentIndex <= 0) {
return;
} else {
if (currentIndex - 1 <= 4 * pageBlock) {
setPageBlock((n) => n - 1);
}
setCurrentIndex((n) => n - 1);
}
} else {
if (currentIndex >= dump.length) {
return;
} else {
if (4 * (pageBlock + 1) <= currentIndex + 1) {
setPageBlock((n) => n + 1);
}
setCurrentIndex((n) => n + 1);
}
}
};
return (
<div>
<div>pagination test</div>
<div style={{ fontSize: "24px" }}>current Indx: {currentIndex}</div>
<div style={{ fontSize: "24px" }}>current page block: {pageBlock}</div>
<div style={{ marginBottom: "15px" }} onClick={() => onClickPage("prev")}>
prev
</div>
{pages.map((data, index) => (
<div onClick={() => onClickPageItem(data.id)} key={data.id}>
{data.title}:{index}
</div>
))}
<div style={{ marginTop: "15px" }} onClick={() => onClickPage("next")}>
next
</div>
</div>
);
}

它被称为箭头函数,n是该箭头函数的参数。你应该先读一下箭头函数,然后你就会明白发生了什么。

最新更新