问题
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