React pagination in componentDidMount()



我正在开发一个类似博客的网站,有一个名为PageDetail的页面,其中包含帖子和评论。

我使用 redux 获取注释并设置状态。

componentDidMount() {
this.props.fetchComments(this.props.match.params.id)
this.setCommentsForCurrentPage()
}

我的状态如下所示以进行分页。

state = {
currentPage: 0,
offset: 0,
slicedComments: [],
}

我的切片功能如下。

setCommentsForCurrentPage() {
let slicedComments = this.props.comments
.slice(this.state.offset, this.state.offset + COMMENT_PER_PAGE)
this.setState({ slicedComments });
}

我将此注释传递给注释组件。

<Comments
comments={this.state.slicedComments}
/>

我的问题是;由于注释设置为异步状态,setCommentsForCurrentPage函数立即运行,并且找不到来自redux的任何注释道具。

此类问题的最佳实践是什么?

提前谢谢。

尝试在 Comments 组件中使用 componentDidUpdate 方法。由于你的道具会改变,它会触发重新渲染,你的评论应该会显示出来。

componentDidUpdate(prevProps) {
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}

'

使用componentDidUpdate生命周期函数而不是componentDidMount来确定何时运行setCommentsForCurrentPage()。 将 prevProps 与当前 props 进行比较,如果this.props.comments已更改,请运行setCommentsForCurrentPage()

https://reactjs.org/docs/react-component.html

最新更新