【问题标题】:Update axios request for pagination更新 axios 请求分页
【发布时间】:2020-07-23 18:48:39
【问题描述】:

我有一个显示数据数组的 axios GET 请求,但一次只显示 15 个项目。 API url 使用多个页面,例如example.com/?page=1。我想创建某种分页,我可以在其中选择下一页,它将 GET 请求更改为下一页。如何根据我选择的页码更改 url 页码?

这是我当前的 componentDidMount 请求,所以当我到达该页面时,

componentDidMount() {
    const access_token = JSON.parse(localStorage['appState']).user
        .access_token;

    const config = {
        headers: {
            Authorization: 'Bearer ' + access_token,
        },
    };

    axios
        .get('https://exammple.com/api/v1/job?page=1', config)

        .then((response) => {
            // handle success
            console.log(response.data.data);
            this.setState({ jobs_info: response.data.data });
        })
        .catch((error) => {
            if (error.response) {
                // The request was made and the server responded with a status code
                // that falls out of the range of 2xx
                console.log(error.response.data);
                console.log(error.response.status);
                console.log(error.response.headers);
            } else if (error.request) {
                // The request was made but no response was received
                // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
                // http.ClientRequest in node.js
                console.log(error.request);
            } else {
                // Something happened in setting up the request that triggered an Error
                console.log('Error', error.message);
            }
            console.log(error.config);
        });
}

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    我想创建某种分页,我可以在其中选择下一页

    像这样创建分页组件:

    function PageSelector(props) {
      const pages = [];
    
      for (let i = 1; i <= props.numberOfPages; i++) {
        pages.push(
          <div key={i} onClick={() => props.handleClick(i)}>{i}</div>
        );
      }
    
      return <div>{pages}</div>;
    }
    

    此组件呈现页面按钮(它需要良好的样式,但为了清楚起见,我保留它)。

    每次点击带有页码的按钮都会使用handleClick函数更新&lt;App /&gt;组件状态:

    export default class App extends React.Component {
      constructor(props) {
        // ...
        this.state = {
          currentPage: 1,
          numberOfPages: 5
        };
      }
    
      handleClick(value) {
        this.setState({ currentPage: value });
      }
      
      render() {
        return (
          <div className="App">
            <PageSelector handleClick={this.handleClick} />
          </div>
        );
    }
    
      // ...
    }
    

    currentPage 值被传递给CommentsView 组件以请求 API。 CommentsView 组件数据会在每次 currentPage 更改时更新。

    class CommentsView extends React.Component {
      constructor(props) { /* ... */ }
    
      componentDidMount() {
        this.getComments(this.props.postId);
      }
    
      componentDidUpdate() {
        this.getComments(this.props.postId);
      }
    
      getComments(postId) {
        axios
          .get(`https://jsonplaceholder.typicode.com/posts/${postId}/comments`)
          .then(response => this.setState({ comments: response.data }))
          .catch(error => console.log(error));
      }
    
      render() { /* ... */ }
    }
    

    您需要同时使用两种生命周期方法 - componentDidMountcomponentDidUpdate。第一次在组件第一次渲染时运行,第二次在每次组件更新时运行。

    这是根据您选择的页码更改 URL 的方法。


    这里是完整的示例代码,您可以用作参考:

    import React from "react";
    import axios from "axios";
    
    export default class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          currentPage: 1,
          numberOfPages: 5
        };
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick(value) {
        this.setState({ currentPage: value });
      }
    
      render() {
        return (
          <div className="App">
            <CommentsView postId={this.state.currentPage} />
            <PageSelector
              currentPage={this.state.currentPage}
              numberOfPages={this.state.numberOfPages}
              handleClick={this.handleClick}
            />
          </div>
        );
      }
    }
    
    function PageSelector(props) {
      const itemStyle = {
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        width: "30px",
        height: "30px",
        margin: "0 5px",
        border: "1px solid"
      };
    
      const pages = [];
    
      for (let i = 1; i <= props.numberOfPages; i++) {
        pages.push(
          <div key={i} onClick={() => props.handleClick(i)} style={itemStyle}>
            {i}
          </div>
        );
      }
    
      return <div style={{ display: "flex" }}>{pages}</div>;
    }
    
    class CommentsView extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          comments: []
        };
      }
    
      componentDidMount() {
        this.getComments(this.props.postId);
      }
    
      componentDidUpdate() {
        this.getComments(this.props.postId);
      }
    
      getComments(postId) {
        axios
          .get(`https://jsonplaceholder.typicode.com/posts/${postId}/comments`)
          .then(response => this.setState({ comments: response.data }))
          .catch(error => console.log(error));
      }
    
      render() {
        const comments = this.state.comments.map(comment => (
          <li key={comment.id}>{comment.body}</li>
        ));
    
        return comments.length > 0 ? <ul>{comments}</ul> : <span>loading</span>;
      }
    }
    

    (link to codesandbox.io)

    【讨论】:

    • 感谢您的解决方案,但我遇到了一个问题,即组件不断更新,直到出现“尝试次数过多”错误。我还注意到在我的实现和沙盒代码中,当您更改页面时,内容会非常混乱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 2021-09-12
    • 2019-03-13
    • 1970-01-01
    • 2021-04-09
    • 2019-08-09
    • 2020-07-05
    相关资源
    最近更新 更多