【问题标题】:My React function gets called twice, with the second call setting values incorrectly我的 React 函数被调用了两次,第二次调用设置值不正确
【发布时间】:2021-10-31 18:31:11
【问题描述】:

我有一个基于 api 计算页面和页面按钮的函数。在按钮内部被渲染并且它们具有 onClick 功能。当我单击按钮时,应该会发生这种情况:

  • 设置当前页码并将其写入状态
  • 调用获取文本元素根据当前页面显示的api
  • 基于 api 评估页面按钮和数字,并用 css 类标记当前页面

事件处理程序:

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中有一个方便的值,称为“活动”(links.active),它是一个布尔值,如果设置为true,则表示该页面是当前页面。然后我添加一个类“标记页面”以突出显示我当前在该页面上。如果我 {console.log(links.label)} 我看到它被调用了两次,第一次是正确的值,第二次是之前点击的值。所以只有当我再次重新加载页面时它才能正常工作。

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

我昨天和今天一直在做,现在不知道了。

【问题讨论】:

    标签: javascript reactjs function button reloading


    【解决方案1】:

    把你的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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      相关资源
      最近更新 更多