如何在点击反应时触发组件

  • 本文关键字:组件 reactjs
  • 更新时间 :
  • 英文 :


我有一个应用程序要在表中显示。我正在从django rest framework获取api,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;

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

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

你能在按钮上添加一个onClick事件来再次获取吗?

<button onClick={() => call your api method here}><button/>

最新更新