[英]Pagination works from the second click
I have such a problem with pagination: it switches to another page only from the second click.我对分页有这样的问题:它仅从第二次单击切换到另一个页面。 When I click on page 2, it also remains on page 1, and only from the second time it switches to page 2. Also with the rest of the pages.
当我单击第 2 页时,它也保留在第 1 页上,并且仅从第二次切换到第 2 页。还有页面的 rest。 I did pagination component like this:
我做了这样的分页组件:
const Paginator = ({
total,
startPage = 1,
limit = 2,
totalPages = null,
onMovePage = null,
}) => {
const [hovered, setHovered] = useState(false);
const handleEnter = () => {
setHovered(true);
};
const handleLeave = () => {
setHovered(false);
};
const style = hovered ? { left: "-230px" } : {};
const [currentPage, setCurrentPage] = useState(startPage);
function range(start, stop, step) {
if(typeof stop=='undefined'){/*one param defined*/stop=start;start=0}
if(typeof step=='undefined'){step=1}
if((step>0&&start>=stop)||(step<0&&start<=stop)){return[]}
let result=[];
for(let i=start;step>0?i<stop:i>stop;i+=step){result.push(i)}
return result;
};
return (
<>
...
{range(1, totalPages+1).map(p => (
<PagItem key={p} handleClick={ () => {setCurrentPage(p); onMovePage && onMovePage({currentPage})} } title={p} name={p} />
))}
...
</>
}
And using it in softwares component:并在软件组件中使用它:
const PER_PAGE = 2;
const Softwares = () => {
const [softwares, setSoftwares] = useState([]);
const [total, setTotal] = useState(null);
const [totalPages, setTotalPages] = useState(null);
const onFetchData = ({ currentPage }) => {
console.log('currentPage in onFetchData', currentPage)
fetch(`http://127.0.0.1:8000/api/software/?p=${currentPage}&per_page=${PER_PAGE}`)
.then(response => response.json())
.then(data => {
setSoftwares(data.results);
setTotal(data.count);
setTotalPages(data.total_pages);
})
}
useEffect(() => {
onFetchData({ currentPage: 1 })
}, []);
return (
<>
...
{softwares.map(s => (
<Article key={s.id} pathname={s.id} title={s.title} image={s.image} pubdate={s.pub_date} icon={s.category.parent.img} categoryID={s.category.id} categoryName={s.category.name} dCount={s.counter} content={s.content} />
))}
<Paginator totalPages={totalPages} total={total} onMovePage={onFetchData} limit={PER_PAGE} />
...
</>
);
};
So why is it happening?那么为什么会这样呢?
Change the below更改以下
<PagItem key={p} handleClick={ () => {setCurrentPage(p); onMovePage && onMovePage({currentPage})} } title={p} name={p} />
to至
<PagItem key={p} handleClick={ () => {setCurrentPage(p); onMovePage && onMovePage({currentPage:p})} } title={p} name={p} />
Because you're assuming your state currentPage
is set by the time you call onMovePage
which isn't true.因为您假设您的 state
currentPage
是在您调用onMovePage
时设置的,这是不正确的。 Rely on the p
to move to that page
instead of state which will be set asynchronously.依靠
p
移动到该page
,而不是异步设置的 state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.