首页 > 解决方案 > 如何在点击反应时触发componentdidmount

问题描述

我有一个要在桌子上显示的应用程序。我正在从中获取 api django rest framework,API 是分页的。因此,当我加载 react 应用程序时,它默认加载第一页(例如它调用http://localhost:8000/cluster/37/tasks?page=1)。我有一个下一个按钮。我试图在单击下一步时转到下一页(例如它应该调用http://localhost:8000/cluster/37/tasks?page=2)。

如何尝试在单击下一步按钮时触发提取?谢谢。下面是我的代码示例:

class TasksApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      columnDefs: [
        { headerName: 'Temp RowNumber', valueGetter: 'node.rowIndex'},
        { headerName: 'Status', field: 'status' },
        { headerName: 'Params', field: 'joint_params' },
        { headerName: 'Total Pages', field: 'total_pages' },
        { headerName: 'Total Results', field: 'total_results' },
      ],
      defaultColDef: { resizable: true },
      rowData: null,
      dataLength: 0,
      id: this.props.location.state.id,
      task: this.props.match.params.value,
      headerHeight: 39,
      rowHeight: 49,
      paginationPageSize: 200,
      totalPages: null,
      currentPage: null,
      pageSize: null,
      pageNumberList: [],
      pageSizeList: [],
      startIndex: 0,
      endIndex: 5,
    };
  }

  onGridReady = params => {
    this.gridApi = params.api;
  };

  componentDidMount(){
    fetch(`http://localhost:8000/cluster/${this.state.id}/tasks?page=${this.state.page}`, options)
    .then(res => res.json())
    .then(data => this.setState({
      rowData: data['results'],
      dataLength: data['totalDataOnPage'],
      totalData: data['totalData'],
      currentPage: data['currentPage'],
      totalPages: data['totalPages'],
      nextLink: data['nextPage'],
      previousLink: data['previousPage']
    }))
    .catch(err => console.log(err))
  }


  onPaginationChanged = () => {
    let list_pages = []
    if (this.gridApi) {
      console.log('total pages', this.state.totalPages)

      for (var i = 1; i <= this.state.totalPages; i++) {
        list_pages.push(i);
      }
      this.setState({ pageNumberList: list_pages })
    }
  };


  onBtNext = () => {
//how do I trigger the componentDidMount to load the next page number on click next
    var url = new URL(this.state.nextLink);
    var pagenumber = url.searchParams.get("page");
    this.setState({ page: pagenumber })
  }

  render() {
    const pagelist = this.state.pageNumberList.slice(this.state.startIndex, this.state.endIndex)
    return (
      <>
//code truncated to show the `next`, the table and another part of pagination was here. 
.......
next button below..

                    {!pagelist.includes(this.state.totalPages) ?
                      <PageDirection onClick={() => this.onBtNext()} style={{marginLeft: '15px'}}>
                        <ChevronRight style={{ padding: '5px' }} />
                      </PageDirection> 
                      : null
                    }
                  </PaginationSectorTwo>
                </div>
              </Fragment>
            </TableContent>
          </InnerWrapper>
        </Wrapper>
      </>

    )
  }

}

export default TasksApp;

标签: reactjs

解决方案


您不应尝试componentDidMount在单击时触发,因为componentDidMount在组件的生命周期中仅执行一次,即在组件安装后立即执行。

您应该更改onBtNext()函数以获取数据。


推荐阅读