【发布时间】:2021-08-11 02:50:49
【问题描述】:
我正在创建一个表格应用程序组件,该组件从 API (https://retoolapi.dev/HKpCV2/data) 获取数据,其中 25 项数据分为 3 页(每页限制 10 项)。虽然第一页的数据正确呈现,但我无法使用为按钮 first、previous、next 和 last 创建的功能导航到其他页面。所有按钮都不起作用,我无法解决此问题。下面显示了代码中每个部分的详细分解:
this.state & componentDidMount 到 Fetch API
constructor(props){
super(props);
this.state = {
err: null,
isLoaded: false,
users: [],
curr_page: 1,
per_page: null,
total: 0
}
}
componentDidMount(){
const { curr_page } = this.state;
fetch(`https://retoolapi.dev/HKpCV2/data?_page=${curr_page}`)
.then(
(res) => {
if(res.ok) {
if(res.status >= 400){
throw new Error("Server responds with error!")
}
return res.json();
}
})
.then(
(data) => {
this.setState({
...this.state,
users: data,
isLoaded: true
});
},
(err) => {
this.setState({
isLoaded: true,
err
});
}
);
}
按钮功能
goToFirstPage = (e) => {
e.preventDefault()
this.setState({
...this.state,
curr_page: 1
})
}
goToPrevPage = () => {
this.setState({
...this.state,
curr_page: this.state.curr_page - 1
})
}
goToNextPage = () => {
this.setState({
...this.state,
curr_page: this.state.curr_page - 1
})
}
goToLastPage = () => {
this.setState({
...this.state,
curr_page: null //replace with total number of pages
})
}
Main.js
render(){
const { users, isLoaded } = this.state;
const renderData = users.map((user) => {
return(
<tbody key={user.id}>
<td>{user.id}</td>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
</tbody>
)
})
if(!isLoaded){
return(
<p>Loading...</p>
)
}
return(
<div>
<table>
<thead>
<th>S/N</th>
<th>FN</th>
<th>LN</th>
</thead>
{renderData}
</table>
<div>
<button onClick={this.goToFirstPage}><<</button>
<button onClick={this.goToPrevPage}><</button>
<button onClick={this.goToNextPage}>></button>
<button onCLick={this.goToLastPage}>>></button>
</div>
</div>
)
}
【问题讨论】:
标签: reactjs