【问题标题】:Paginate API call in React ComponentReact 组件中的分页 API 调用
【发布时间】:2019-03-04 01:14:48
【问题描述】:

我想对 Api 调用的结果进行分页。 我正在使用这样的 Axios 进行 Api 调用

apiCall() {
const API = `http://www.omdbapi.com/`;
axios.get(API, {
        params: {
            apikey: process.env.REACT_APP_MOVIECALL_API_KEY,
            type: 'movie',
            s: 'superhero',
            page: this.state.pageCount
        }
    })
    .then(res => {
        const superheroes = res.data.Search
        const totalResults= parseInt(res.data.totalResults)
        this.setState({
            totalResults
        });
        this.setState({
            superheroes
        })
    })
    .catch((error) => {
        console.log(error);
    });
}

当组件被挂载时,调用的函数就是这样

  componentDidMount() 
    { 
     this.apiCall();
    }

在渲染函数中,我映射每个搜索结果(在 api 调用中,s 参数是搜索选项) 对于每个结果,我都会显示一个按钮,单击该按钮会显示该电影的相关信息。 默认情况下,该 API 每次调用显示 10 个结果,但此特定搜索总共有 123 个结果。 现在通过更新我设置为 this.state.pageCount 的调用中的参数页面 它显示了与该页面相关的 10 部不同的电影,目前我在状态中对 pageCount 进行硬编码以确保它可以正常工作,并且相应的页码显示了 10 部电影的正确列表。

现在我想通过更新页码对结果进行分页,所以当您单击下一步或数字 3/4/5 时,组件会加载正确的相应结果,我尝试了几个与做出反应,但他们不知何故不更新页码。

如果有人能指出我正确的方向或知道一个简单的解决方案,我会全力以赴。

以下代码是整个组件,以了解我想要做什么。

到目前为止我所拥有的似乎正在工作,所以我要求的是 为这个特定的分页更简单更优雅的方式 情况。

export class MovieDetails extends Component {
  constructor(props){
    super(props)
    this.state = {
      superheroes: [],
      clicked: false,
      activeHero: {},
      pageCount: 11,
      totalResults: null,
      currentPage: 1
    }
    this.handleClick = this.handleClick.bind(this);
  }


  handleClick(hero) {
    const checkActive = this.state.activeHero.imdbID === hero.imdbID
    const activeHero = {...hero, active: !checkActive}
    this.setState({
      clicked: !this.state.clicked,
      activeHero
    })
  }    

  apiCall() {
    const API = `http://www.omdbapi.com/`;
    axios.get(API, {
            params: {
                apikey: process.env.REACT_APP_MOVIECALL_API_KEY,
                type: 'movie',
                s: 'superhero',
                page: this.state.pageCount
            }
        })
        .then(res => {
            const superheroes = res.data.Search
            const totalResults = parseInt(res.data.totalResults)
            this.setState({
              totalResults
            });
            this.setState({
                superheroes
            })
        })
        .catch((error) => {
            console.log(error);
        });
  }

  componentDidMount() {
    this.apiCall();
    }

    handlePageChange = (page, e) => {
      this.setState({
        currentPage: page
      });
      this.apiCall(this.setState({pageCount: page}))

    };


  render() {

    const {superheroes, currentPage } = this.state
    return (
        <div>
      {
        superheroes.map((hero, i) => 
            <div className="Results" key={i}>
            <button onClick={() => {this.handleClick(hero)}}> 
            <h1>{hero.Title}</h1>
            {
              this.state.clicked && this.state.activeHero.imdbID === hero.imdbID
                ? <ul>
                    {<div key={i}>
                    Movie Title: <h2> {hero.Title}</h2>
                      Year of Release: <h2>{hero.Year}</h2>
                      ID: <h2>{hero.imdbID}</h2>
                      <div><img className="Poster" alt="movieposter" src={hero.Poster}/></div>
                      </div>
              }
            </ul>
          : null
      }
      </button>
      </div>) 
   }
          <div className="Pagination"> 
          <Pagination
          total={this.state.totalResults}
          limit={10}
          pageCount={this.state.pageCount}
          currentPage={currentPage}
        >
          {({
            pages,
            currentPage,
            hasNextPage,
            hasPreviousPage,
            previousPage,
            nextPage,
            totalPages,
            getPageItemProps
          }) => (
            <div>
              <button
                {...getPageItemProps({
                  pageValue: 1,
                  onPageChange: this.handlePageChange
                })}
              >
                first
              </button>

              {hasPreviousPage && (
                <button
                  {...getPageItemProps({
                    pageValue: previousPage,
                    onPageChange: this.handlePageChange
                  })}
                >
                  {'<'}
                </button>
              )}

              {pages.map(page => {
                let activePage = null;
                if (currentPage === page) {
                  activePage = { backgroundColor: '#fdce09' };
                }
                return (
                  <button
                    {...getPageItemProps({
                      pageValue: page,
                      key: page,
                      style: activePage,
                      onPageChange: this.handlePageChange
                    })}
                  >
                    {page}
                  </button>
                );
              })}

              {hasNextPage && (
                <button
                  {...getPageItemProps({
                    pageValue: nextPage,
                    onPageChange: this.handlePageChange
                  })}
                >
                  {'>'}
                </button>
              )}

              <button
                {...getPageItemProps({
                  pageValue: totalPages,
                  onPageChange: this.handlePageChange
                })}
              >
                last
              </button>
            </div>
          )}
        </Pagination>
          </div>
      </div>

    );
  }
}

【问题讨论】:

    标签: javascript reactjs rest pagination axios


    【解决方案1】:

    在您的 axios.get 函数中,您发送的是 page: this.state.pageCount,但是在您的 handlePageChange 函数中,您正在设置 state.currentPage,这对我来说似乎不正确。

    我也对&lt;button /&gt; 上的onPageChange 事件感到有些困惑。这个按钮是您正在导入的自定义组件(在这种情况下,它应该大写以使其清晰)还是 HTML 按钮?如果它是一个 HTML 按钮,那么您需要使用 onClick 事件,它将事件作为参数传递给 handlePageChange 函数。我猜它是自定义的,虽然从你传递的道具来看,所以值得检查它是否正确发送 page 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-12
      • 1970-01-01
      • 2020-09-14
      • 2019-02-15
      • 2020-08-25
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多