简体   繁体   English

从 api 接收数据时遇到问题

[英]Having trouble receiving data from api

I am new to working with REACT and I am having trouble receiving data from my api.我是使用 REACT 的新手,我无法从我的 api 接收数据。 I am using postman to help me build this project, so I am hoping I used it correctly.我正在使用邮递员来帮助我构建这个项目,所以我希望我能正确使用它。 The app will show up with my table and pagination but not the information from my selected api.该应用程序将显示我的表格和分页,但不会显示来自我选择的 api 的信息。 I am thinking I need to have my api as an array but how would I go about making my api into an array to properly show my data?我在想我需要将我的 api 作为一个数组,但是我将如何将我的 api 变成一个数组以正确显示我的数据? here is my code:这是我的代码:

import axios from "axios";
import _ from "lodash"; //lookup lodash
import Table from "react-bootstrap/Table";

const pageSize = 10;
const Posts = () => {
  const [_posts, set_posts] = useState();
  const [paginatedPosts, setPaginatedPosts] = useState();
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    axios.get("https://swapi.dev/api/people/").then((res) => {
      console.log(res.data);
      set_posts(res.data);
      setPaginatedPosts(_(res.data).slice(0).take(pageSize).value());
    });
  }, []);

  const pageCount = _posts ? Math.ceil(_posts.length / pageSize) : 0;
  if (pageCount === 1) return null;
  const pages = _.range(1, pageCount + 1);

  function pagination(pageNo) {
    setCurrentPage(pageNo);
    const startIndex = (pageNo - 1) * pageSize;
    const paginatedPosts = _(_posts).slice(startIndex).take(pageSize).value();
    setPaginatedPosts(paginatedPosts);
  }

  return (
    <div>
      {!paginatedPosts ? (
        "No data found"
      ) : (
        <Table striped bordered hover className="project--table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Birth Year</th>
              <th>Height</th>
              <th>Mass</th>
              <th>Species</th>
              <th>Home World</th>
            </tr>
          </thead>
          <tbody>
            {paginatedPosts.map((_post, index) => (
              <tr key={index}>
                <td>{_post.name}</td>
                <td>{_post.birth_year}</td>
                <td>{_post.height}</td>
                <td>{_post.mass}</td>
                <td>{_post.species}</td>
                <td>{_post.home_world}</td>
              </tr>
            ))}
          </tbody>
        </Table>
      )}
      <nav className="d-flex justify-content-center">
        <ul className="pagination">
          {pages.map((page) => (
            <li
              className={
                page === currentPage ? "page-item active" : "page-item"
              }
            >
              <p className="page-link" onClick={() => pagination(page)}>
                {page}
              </p>
            </li>
          ))}
        </ul>
      </nav>
    </div>
  );
};

export default Posts;


The api I am using is the starwarsapi

First of all, you always need to check the response body.首先,您总是需要检查响应正文。 In your case it'd be res.data.result to get the list, and it has other properties too, like the total length of records.在您的情况下,获取列表将是 res.data.result ,并且它也具有其他属性,例如记录的总长度。 After fixing that, you'll get the list, but your pagination logic has errors.修复后,您将获得列表,但您的分页逻辑有错误。

An advice is to remove the pagination logic, go step by step, so you can understand better what is happening.一个建议是删除分页逻辑,逐步进行,这样您就可以更好地了解正在发生的事情。 For example, the way you're doing your page size will always be 1 because you're not counting the total data length, you're couting the list length.例如,您处理页面大小的方式将始终为 1,因为您没有计算总数据长度,而是计算列表长度。 So you'll need to use other properties of your response.data object.因此,您需要使用 response.data 对象的其他属性。

Other point that might be useful about the pagination is that you don't really need to paginate on frontend, the api already has a page parameter (10 records per page, like your example).对分页可能有用的另一点是,您实际上并不需要在前端进行分页,api 已经有一个页面参数(每页 10 条记录,如您的示例)。 But if you want to create the pagination, you don't need lodash to do it, search for plain javascript solutions.但是如果你想创建分页,你不需要 lodash 来做,搜索普通的 javascript 解决方案。

The posts resides in results in res.data so you need to set posts to res.data.results帖子位于 res.data 中的结果中,因此您需要将帖子设置为 res.data.results

useEffect(() => {
    axios.get("https://swapi.dev/api/people/").then((res) => {
      console.log(res.data);
      set_posts(res.data.result);

    });
  }, []);

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

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