React Component中的分页API调用

时间:2019-03-03 13:30:36

标签: javascript reactjs rest pagination axios

我想对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();
    }

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

现在,我想通过更新页码来对结果进行分页,因此当您单击next或数字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>

    );
  }
}

1 个答案:

答案 0 :(得分:0)

SELECT p.*, (PA-age)*age AS PS FROM (SELECT price, age, price * age AS PA FROM P ) p; 函数中,您正在发送axios.get,但是在page: this.state.pageCount函数中,您正在设置handlePageChange,这对我来说似乎不正确。

我对state.currentPage上的onPageChange事件也有些困惑。此按钮是您要导入的自定义组件(在这种情况下,应使用大写字母以使其清晰可见)还是HTML按钮?如果是HTML按钮,则需要使用<button />事件,该事件会将事件作为参数传递给onClick函数。我猜它是自定义的,尽管从传递的道具中可以看出来,所以值得检查一下它是否正确发送了handlePageChange值。