繁体   English   中英

如何在 ReactJS 中分页时获取数据?

[英]how to fetch the data while pagination in ReactJS?

我要解决的是,在获取数据时将页面value作为参数传递。 并且还将默认分页value设置为"1"

端点网址: http://localhost:8000/api/blog_list?page=

api数据:

{
    "count": 3,
    "next": "http://localhost:8000/api/blog_list?page=2",
    "previous": null,
    "results": [
        {
            "id": 6,
            "url": "http://localhost:8000/api/blog_detail/test3",
            "title": "test3",
            "slug": "test3",
            "image": "http://localhost:8000/media/blog/author.jpg",
            "description": "test3",
            "created_on": "2020-05-13T13:36:45Z",
            "status": true,
            "category": [
                1
            ]
        },
        {
            "id": 10,
            "url": "http://localhost:8000/api/blog_detail/test3",
            "title": "Hamid",
            "slug": "test3",
            "image": "http://localhost:8000/media/blog/person_2_2beHkt1.jpg",
            "description": "test",
            "created_on": "2020-05-13T14:59:30.855849Z",
            "status": true,
            "category": [
                2
            ]
        }
    ]
}


./src/BlogList.js

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      value: "",
      response: "",
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData = async () => {
    try {
      const response = await fetch(
        `http://localhost:8000/api/blog_list?page=${value}`
      );
      const JsonResponse = await response.json();
      this.setState({ response: JsonResponse });
    } 
    catch (error) {
      console.log(error);
    }
  };

  render() {
    const { response } = this.state;

    if (!response) {
      return "Loading...";
    }

    return (
      <div>
        {response.results.map((response) =>(

            <div class="col-md-12">

                <h3> {response.title} </h3>

            </div>


        ))}
      </div>
    );
  }
}

export default App;

我不确定我是否正确理解了您的问题,但是如果您想将 state 值作为参数添加到此提取中,您可以使用字符串连接传递该值:

常量响应=等待获取( http://localhost:8000/api/blog_list?page=${value} );

http://localhost:8000/api/blog_list?page= + this.state.value

我相信一个问题是您没有在 fetch 调用中使用 state。 它应该看起来像这样。

const response = await fetch(
  `http://localhost:8000/api/blog_list?page=${this.state.value}`
);

如果您想将 state 中的值初始化为1 ,那么您可以像这样初始化 state :

this.state = {
  value: "1",
  response: "",
};
fetchData = async () => {
const { value } = this.state
try {
  const response = await fetch(
    `http://localhost:8000/api/blog_list?page=${value}`
  );
  const JsonResponse = await response.json();
  this.setState({ response: JsonResponse });
} 
catch (error) {
  console.log(error);
}

};

fetchData 中未定义“值”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM