我的 React 函数被调用两次,第二次调用设置值不正确

My React function gets called twice, with the second call setting values incorrectly

我有一个函数可以根据 api 计算页面和页面按钮。在按钮内部得到渲染,并且它们具有 onClick 功能。当我点击按钮时,这应该会发生:

事件处理程序:

handleClick(event) {
        let currentPage = Number(event.target.id)
        localStorage.setItem("currentPage", 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>
)

组件如下所示:

function Paging(props) {
    const apiPaging = props.state.apiPaging
    const apiPagingSliced = apiPaging.slice(1, -1) 
    
    const renderPageNumbers = apiPagingSliced.map((links, index)  => {
        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"> 
              {renderPageNumbers}
         </div>
           )

所以发生的是 Paging() 函数被调用了两次。 api 中有一个名为“active”(links.active)的方便值,它是一个布尔值,如果设置为 true,则表示该页面是当前页面。然后我添加一个 class “标记页面”以突出显示我当前在该页面上。如果我 {console.log(links.label)} 我看到它被调用了两次,第一次是正确的值,第二次是之前点击的值。所以只有当我重新加载页面时它才能正常工作。

即如果我单击第 2 页,它会停留在第 1 页并标记第 1 页。如果我然后单击第 3 页,它会标记第 2 页。并且(afaik)Paging()仅在结束时被调用一次我唯一的class(正文)。

我昨天和今天都在看,现在不知道了。

将您的 handleClick 函数更改为此。

handleClick(event) {
window.scrollTo({
  top: 0,
  behavior: '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