https://codesandbox.io/s/04r2qwv5jv
getPlayerValues() {
let comments = [];
fetch("https://jsonplaceholder.typicode.com/comments")
.then(response => response.json())
.then(json => {
comments = json;
// comments = comments.slice(0,3);
this.setState({ comments: comments });
this.setState({ activeComments: comments.slice(0, 10) });
//console.log(comments);
});
}
render() {
let listView = this.state.activeComments.map(comment => (
<RecipeReviewCard
key={comment.id}
commentId={comment.id}
cardBelowContent={comment.body}
cardContent={comment.name}
comment={comment}
/>
));
return this.state.comments.length > 0 ? (
<div>
<LinearDeterminate />
{listView}
<br />
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={10}
totalItemsCount={this.state.comments.length}
pageRangeDisplayed={5}
onChange={this.handlePageChange}
/>
</div>
) : (
""
);
}
答案 0 :(得分:1)
最好的做法是使用loading
标志,该标志在开始请求之前就设置为true
,然后在请求返回时设置为false
。然后,您可以使用该标志有条件地渲染进度条!
getPlayerValues() {
this.setState({ loading: true });
fetch("https://jsonplaceholder.typicode.com/comments")
.then(response => response.json())
.then(comments => {
this.setState({
loading: false,
comments: comments
});
});
}
render() {
const { comments, loading } = this.state
// active comments can be derived so no need to store them in state :)
const activeComments = comments.slice(0, 10);
// render your progress bar
if(loading) return <LinearDeterminate />;
// render everything else once loading === false
return (
<div>
{activeComments.map(comment => (
<RecipeReviewCard
key={comment.id}
comment={comment} {/* already passing comment prop here */}
commentId={comment.id} {/* so there's need to pass the these props */}
cardContent={comment.name} {/* just access via this.props.comment */}
cardBelowContent={comment.body}
/>
))}
</div>
)
}