实现思路
- 初始化状态:在组件的
state
中定义当前页码 page
,默认值为 1,以及存储评论数据的数组 comments
。
- 首次加载:利用
componentDidMount
生命周期方法,在组件挂载后,根据当前 page
值(初始为 1)调用获取评论数据的函数。
- 点击下一页:定义一个处理下一页点击的函数
handleNextPage
,在该函数中更新 page
状态值,然后根据新的 page
值再次调用获取评论数据的函数。
关键代码片段
import React, { Component } from 'react';
class ProductReview extends Component {
constructor(props) {
super(props);
this.state = {
page: 1,
comments: []
};
this.handleNextPage = this.handleNextPage.bind(this);
}
componentDidMount() {
this.fetchComments();
}
fetchComments = () => {
const { page } = this.state;
// 这里应该替换为实际的API请求
// 假设API返回的数据格式为{data: [评论数据数组]}
fetch(`/api/comments?page=${page}`)
.then(response => response.json())
.then(data => {
this.setState({
comments: [...this.state.comments, ...data.data]
});
});
}
handleNextPage() {
this.setState(prevState => ({
page: prevState.page + 1
}), () => {
this.fetchComments();
});
}
render() {
const { comments } = this.state;
return (
<div>
<ul>
{comments.map((comment, index) => (
<li key={index}>{comment}</li>
))}
</ul>
<button onClick={this.handleNextPage}>下一页</button>
</div>
);
}
}
export default ProductReview;