显示最后一页时如何隐藏“下一页”按钮?
我使用以下代码从特定页面的 API 获取数据:
const [ loading, setLoading ] = useState(true);
const [ showsData, setShowsData ] = useState(undefined);
const [ newData, setNewData ] = useState(undefined);
const [pageNumber, setPageNumber] = useState(props.match.params.pageno);
useEffect(() => {
async function fetchData() {
try {
const { data } = await axios.get('http://api.tvmaze.com/shows?page=' +pageNumber);
setShowsData(data);
setLoading(false);
} catch (e) {
console.log(e);
}
}
fetchData();
}, [ pageNumber ]);
现在,对于分页,我尝试隐藏下一个按钮直到最后一页,我可以通过获取最后一页后面的页面的数据来获取最后一页。如果它返回空[],我就会知道我找到了最后一页并且可以隐藏下一页按钮。为此,我创建了另一个 useEffect:
useEffect(() => {
async function fetchData() {
try {
const { data } = await axios.get('http://api.tvmaze.com/shows?page=' +pageNumber+1);
setNewData(data);
setLoading(false);
} catch (e) {
console.log(e);
}
}
fetchData();
}, [ pageNumber ]);
为了隐藏下一个按钮,我执行以下操作:
{ newData!==[] && <Link className='showlink' to {`/shows/page/${parseInt(pageNumber)+1}`}>
Next
</Link>}
这不起作用,即使在最后一页之后也会显示下一个按钮。我该如何解决这个问题?
I am getting data from an API for a particular page using the below code:
const [ loading, setLoading ] = useState(true);
const [ showsData, setShowsData ] = useState(undefined);
const [ newData, setNewData ] = useState(undefined);
const [pageNumber, setPageNumber] = useState(props.match.params.pageno);
useEffect(() => {
async function fetchData() {
try {
const { data } = await axios.get('http://api.tvmaze.com/shows?page=' +pageNumber);
setShowsData(data);
setLoading(false);
} catch (e) {
console.log(e);
}
}
fetchData();
}, [ pageNumber ]);
Now, for pagination I am trying to hide the next button until the last page, I can get the last page by fetching data for the page after it. If it returns empty [], I will know that I found the last page and can hide the next button. To do this I created another useEffect:
useEffect(() => {
async function fetchData() {
try {
const { data } = await axios.get('http://api.tvmaze.com/shows?page=' +pageNumber+1);
setNewData(data);
setLoading(false);
} catch (e) {
console.log(e);
}
}
fetchData();
}, [ pageNumber ]);
To hide the next button I am doing the following:
{ newData!==[] && <Link className='showlink' to {`/shows/page/${parseInt(pageNumber)+1}`}>
Next
</Link>}
This does not work and the next button is shown even after the last page. How can I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
newData
的初始状态设置为空的Array
。Set initial state of
newData
to an emptyArray
.