不确定在哪里将进度条组件插入api调用

时间:2018-12-21 21:53:55

标签: javascript html reactjs redux material-ui

  • 我正在尝试学习ui的材料
  • 我知道进度条。
  • 但是我需要加载直到我的数据没有加载。
  • 不确定在何处插入进度条组件。
  • 您能告诉我在进行api调用时如何解决它。以便将来我自己修复
  • 在下面提供我的代码段。
  • 我所有的代码都在ReceipeReviewCardList.js中

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

1 个答案:

答案 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>
  )

}