在 componentDidMount() 中反应分页 [英] React pagination in componentDidMount()

查看:34
本文介绍了在 componentDidMount() 中反应分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a blog-like website and there is a page called PageDetail with the post and comments.

我使用 redux 获取评论并设置状态.

I fetch the comments with redux and set the state.

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

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

My state is shown as below to do the pagination.

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 组件.

And I pass this comments to the Comments component.

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

我的问题是;由于注释设置为状态 async,因此 setCommentsForCurrentPage 函数立即运行,并且找不到来自 redux 的任何注释属性.

My problem is; since the comments is set to the state async, setCommentsForCurrentPage function runs immediately, and it cannot find any comment prop coming from the redux.

解决此类问题的最佳做法是什么?

What is the best practice for this kind of a problem?

提前致谢.

推荐答案

尝试在 Comments 组件中使用 componentDidUpdate 方法.因为你的 props 会改变,它会触发重新渲染,你的评论应该会出现.`

Try using componentDidUpdate method in your Comments component. Since your props will change, it will trigger the rerendering and your comments should show up.`

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

`

这篇关于在 componentDidMount() 中反应分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆