【发布时间】:2020-12-18 04:41:40
【问题描述】:
我正在学习 javascript 和 React,挑战(在 Hackerrank 实践中)是从具有多个页面的 API 获取数据。按钮的数量应该与页面数一样多,单击每个按钮时,该特定页面的数据应如下所示:
这是我写的组件:
import React from 'react';
const url = "https://jsonmock.hackerrank.com/api/articles?page=";
const default_page = 1;
class Articles extends React.Component {
state = {
pageCount: 1,
body: {},
currentPage: 1,
error: null,
isLoading: false,
data: []
};
componentDidMount(){
this.setState({isLoading: true});
fetch(url+default_page)
.then(response => response.json())
.then(body => this.setState({
pageCount: body.total_pages,
data: body.data,
body: body,
}))
.catch(err => this.setState({error: err}));
}
pageButtonGenerator(){
if(this.state.body){
let pageButtons=[];
for(var i=1; i<=this.state.pageCount; i++){
const id = i; //need this to use in event handler, BUT WHY DOES i NOT WORK (the value is always i=this.state.pageCount)
pageButtons.push(<button data-testid="page-button" key={"page-button-"+i} onClick={(e) => this.buttonClickHandler(id)}>{i}</button>);
}
return pageButtons;
}
else{
return <button data-testid="page-button" key="page-button-1">1</button>
}
}
buttonClickHandler = (pageNum) => {
// console.log(pageNum);
this.setState({isLoading: true});
fetch(url+pageNum)
.then(response => response.json())
.then(body => this.setState({
pageCount: body.total_pages,
data: body.data,
body: body,
currentPage: pageNum
}))
.catch(err => this.setState({error: err}));
// this.titlesGenerator();
}
titlesGenerator = () => {
if(this.state.data){
return this.state.data.map((element,index) => {
if(element.title){ return <li key={"title-"+index+1} data-testid="result-row">{element.title}</li> }
else{ return null }
})
// console.log(this.state.data);
}
}
render() {
return (
<React.Fragment>
<div className="pagination">
{this.pageButtonGenerator()}
</div>
<ul className="results">
{this.titlesGenerator()}
</ul>
</React.Fragment>
);
}
}
export default Articles;
虽然我的代码通过了测试用例,但如果我做对了,我不是很有信心。我有这样的疑问:
- 我应该一次性获取所有页面以避免多次网络调用,还是应该在每次单击页面按钮时进行调用?
- 我生成按钮的方式是否正确(参见
pageButtonGenerator)? - 在
pageButtonGenerator的for 循环中,我是否以正确的方式调用onClick 处理程序?我试图直接传递变量“i”,但它总是 = 6(循环的退出值)。我很难理解为什么变量 i 也是 6。我认为关闭将确保该值始终正确.. - 我应该如何处理状态中存储的内容以及应该派生和不存储的内容?
接受建设性的批评。谢谢
【问题讨论】:
标签: javascript reactjs design-patterns pagination fetch-api