从输入传递值以在React.js中进行分页

时间:2019-05-22 11:33:26

标签: javascript jquery reactjs

我试图在react 16项目上实现非常简单的分页功能,我的想法是将按钮值传递给api查询以获取“&page =“号,然后导航至第二页,第三页,依此类推。 我使用unsplash API来消费图片。我认为“上一个,下一个”按钮应该就足够了,但是我找不到一种可以进行很多更改的好方法。

我尝试了一些在这里找到的解决方案。但没有一个适用于我的简单想法。

import React, { Component } from 'react';
import axios from 'axios';
import './App.css';
import ItemList from './components/ItemList';
import Navigation from './components/Navigation';
import SearchImg from './components/SearchImg';
import Pagination from './components/Pagination';
import Footer from './components/Footer';

export default class App extends Component {
    constructor() {
    super();
    this.state = {
      imgs: [],
      loadingState: true
    };
}

componentDidMount() {
  this.performSearch();
}

performSearch = (query = 'guitar') => {
var pagi = [1]; // here is the variable I should pass the values to.


var headers = {
 'Authorization': 'Bearer xxxxxxxxxxxxxxxxxxxx'
}
axios({
method: 'GET',
url: 'https://api.unsplash.com/search/photos?page='+(pagi)+'&per_page=20&query='+(query), 

//(pagi) is where I want to pass the values


headers: headers,
}).then(data => {
this.setState({ imgs: data.data.results, loadingState: false });
})
.catch(err => {
console.log('Error happened during fetching!', err);
});

};

render() {
  return (
  <div className="container">
  <Navigation /> // This is just a hardcode html buttons navigation.

//maybe just adding two buttons, one for prev, one for next should be enough?.

  <div>
  <SearchImg onSearch={this.performSearch} />
  </div>
  {this.state.loadingState
  ? <p style={centrar}>Loading...</p>

  : <ItemList data={this.state.imgs} />}
    <Footer />
  </div>

  );
}
}

1 个答案:

答案 0 :(得分:0)

有两件事

  1. 为什么将pagi创建为数组?无论您在这里提到什么,我都相信pagi应该是一个数字。因此,相反

    var pagi = 1;

  2. 在网址中使用pagi和查询的最佳方法是像这样

    url:https://api.unsplash.com/search/photos?page=${pagi}&per_page=20&query=${query}

正如阿米特(Amit)所说,您应该看看模板文字。