React:为什么分页方法不起作用



im使用generate radouser api,用户名呈现良好,但分页功能不起作用,我不知道我缺少什么。请帮忙。

我在stackblitz上推送了我的代码,以帮助你们轻松调试它。

链接如下:https://stackblitz.com/edit/to-be-continue?file=src%2FApp.js

return (
<div>
<Pagination
postsPerPage={postsPerPage}
totalPosts={myApi.length}
paginate={paginate}
/>
{myApi} // this should be currentPosts not myApi
</div>
);

您应该使用useState使currentPosts动态,使用useEffect监听currentPagemyApi的变化,然后设置相应的currentPosts

const [currentPosts, setCurrentPosts] = useState([])
// ...
useEffect(() => {
// get current post
const indexOfLastPost = currentPage * postsPerPage; // 1 * 10 = 10
const indexOfFirstPost = indexOfLastPost - postsPerPage; // 10 - 10 = 0
setCurrentPosts(myApi.slice(indexOfFirstPost, indexOfLastPost)); // 0 to 10
}, [currentPage, myApi])
// ...
return (
<div>
<div>Page { currentPage }</div>
<Pagination
postsPerPage={postsPerPage}
totalPosts={myApi.length}
paginate={paginate}
/>
{currentPosts}
</div>
);

分叉解决方案:https://stackblitz.com/edit/to-be-continue-swucmd?file=src/App.js

最新更新