我有一個函式,它基于一個api計算頁面和頁面按鈕。里面的按鈕被渲染,它們有一個onClick函式。當我點擊按鈕時,應該會發生以下情況:
事件處理程式:
handleClick(event) {
let currentPage = Number(event.target.id)
localStorage.setItem("currentPage"/span>, currentPage)
this.setState( {
currentPage: currentPage
})
this.fetchApi()
}
然后我回傳處理頁面的組件:
return(
<div>>
<Paging
data = {this}
currentPage = {this.state.currentPage}
state = {this.state}
lastPage = {this.state.lastPage}
handleClick = {this.handleClick}
/>
</div>/span>
)
而這個組件看起來是這樣的:
function Paging(props) {
const apiPaging = props.state.apiPaging。
const apiPagingSliced = apiPaging.slice(1, -1)
const renderPageNumbers = apiPagingSliced.map((links, index) => /span> {
return < button key={index} id={links. label}
onClick={(index)=>props.handleClick(index)}。
className={(links.active ? "mark-page" : "")}。
>{links.label} {console.log(links.label) }
</button>>。
})
return (
<div id = "page-nums"/span>>
{renderPageNumbers}
</div>
)
所以發生的情況是,Paging()函式被呼叫了兩次。在api里面有一個很方便的值,叫做 "active"(links.active),這是一個布林值,如果設定為真,意味著該頁是當前頁。如果我{console.log(links.label)},我看到它被呼叫了兩次,第一次是正確的值,第二次是先前點擊的值。因此,只有當我再次重新加載頁面時,它才能正常作業。
即如果我點擊第2頁,它就會停留在第1頁并標記第1頁。如果我再點擊第3頁,它就會標記第2頁。
我昨天和今天都在研究這個問題,現在已經不知道了。
uj5u.com熱心網友回復:
把你的handleClick函式改為這樣。
handleClick(event) {
window.scrollTo({
top: 0,
behavior: 's smooth'。
});
if (event.target.id >=1) {
let currentPage = Number(event.target.id) 。
localStorage.setItem('currentPage', currentPage) 。
this.setState( {
currentPage: JSON.parse(localStorage. getItem('currentPage'))。)
},()=>{
this.fetchApi()。
});
}
}
在你的fetchApi函式中,你參考了currentPage,如下所示。
const apiQuery = JSON.parse(this.state.currentPage);
但它還沒有更新。
見https://reactjs.org/docs/react-component.html#setstate
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/320738.html
標籤:
上一篇:點擊按鈕后移動到頂部
下一篇:【C#】【MySQL】【GridView】洗掉出現Parameter index is out of range
