React pagination in componentDidMount()

*爱你&永不变心* 提交于 2021-02-11 14:59:55

问题


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

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: [],
}

My slice function is as below.

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

And I pass this comments to the Comments component.

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

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?

Thanks in advance.


回答1:


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);
  }
}

`




回答2:


Use the componentDidUpdate lifecycle function instead of componentDidMount to determine when to run setCommentsForCurrentPage(). Compare the prevProps to the current props and if this.props.comments have changed, run setCommentsForCurrentPage()

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



来源:https://stackoverflow.com/questions/57877014/react-pagination-in-componentdidmount

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!