首页 > 解决方案 > 不确定在哪里插入我的进度条组件以进行 api 调用

问题描述

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>
    ) : (
      ""
    );
  }

标签: javascripthtmlreactjsreduxmaterial-ui

解决方案


最好的办法是使用一个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>
  )

}

推荐阅读