reactjs - 如何在点击反应时触发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;
解决方案
您不应尝试componentDidMount
在单击时触发,因为componentDidMount
在组件的生命周期中仅执行一次,即在组件安装后立即执行。
您应该更改onBtNext()
函数以获取数据。
推荐阅读
- python - 从python中的json文件中提取一组特定的数据
- javascript - 如何在刷新的页面上显示单选按钮选择
- javascript - Typescript / React:如何使用键构造对象:值作为[字符串]:[ReactComponent]
- python - 使用前一个组行在数据框组中分配值
- asp.net - Asp.net mvc 项目和 webapi 控制器共享会话 cookie 的问题
- linux - ElasticSearch 中的超时更改不起作用
- python - 在 Python 中,添加导入根路径后无法导入当前模块
- c# - 如何拦截outlook发件箱发送事件
- html - Dropzone.js 无法映射到视图模型
- java - 如何将多个列表合并为一个大小不同的列表