将页码添加到url-反应分页

时间:2020-07-10 22:06:00

标签: reactjs pagination react-hooks

我正在尝试将页码添加到url中(在useEffect函数的末尾),但是现在导航到另一个页面将不再起作用,每次我单击第2页只是导航回到第1页有人可以在这里看到我做错了吗?我添加了List组件,分页组件和app.js。

BooksList.js

import React, { useState, useEffect } from "react";

import queryString from "query-string";
import Books from "./Books";
import Pagination from "./Pagination";
import axios from "axios";
import { useHistory, useLocation } from "react-router-dom";

import { Container } from "react-bootstrap";

const BooksList = () => {
  const location = useLocation();
  const history = useHistory();
  const path = window.location.pathname;
  const initialQueryString = queryString.parse(location.search);
  const initialPageNumber = Number(initialQueryString.page) || 1;

  const [books, setBooks] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [currentPage, setCurrentPage] = useState(initialPageNumber);
  const [booksPerPage, setBooksPerPage] = useState(5);

  useEffect(() => {
    const fetchBooks = async () => {
      try {
        setError(false);
        setLoading(true);
        const res = await axios.post("http://nyx.vima.ekt.gr:3000/api/books");

        setBooks(res.data.books);

        setLoading(false);
      } catch (err) {
        console.log(err);
        setError(true);
        setLoading(false);
        setBooks([]);
      }
    };

    fetchBooks();
    history.push(`${path}?page=${currentPage}`);
  }, [currentPage, history, path]);

  const indexOfLastBook = currentPage * booksPerPage;
  const indexOfFirstBook = indexOfLastBook - booksPerPage;
  const currentBooks = books.slice(indexOfFirstBook, indexOfLastBook);
  const paginate = pageNumber => setCurrentPage(pageNumber);

  if (error) return <div>Error message</div>;

  return (
    <Container>
      <Books books={currentBooks} loading={loading} />
      <Pagination
        booksPerPage={booksPerPage}
        booksAmount={books.length}
        paginate={paginate}
      />
    </Container>
  );
};

export default BooksList;

Pagination.js

import React from "react";

const Pagination = ({ booksPerPage, booksAmount, paginate }) => {
  const pageNumbers = [];

  for (let i = 1; i < Math.ceil(booksAmount / booksPerPage); i++) {
    pageNumbers.push(i);
  }

  return (
    <div className="container mt-5">
      <nav>
        <ul className="pagination">
          {pageNumbers.map(number => {
            return (
              <li className="page-item" key={number}>
                <a
                  href="!#"
                  onClick={() => paginate(number)}
                  className="page-link"
                >
                  {number}
                </a>
              </li>
            );
          })}
        </ul>
      </nav>
    </div>
  );
};

export default Pagination;

App.js

import "./App.css";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import BooksList from "./components/BooksList";

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={BooksList} />
        <BooksList />
      </Switch>
    </Router>
  );
};

export default App;

1 个答案:

答案 0 :(得分:1)

在Pagination.js的onClick方法中添加以下行:

e.preventDefault();

代码如下:

return (
    <div className="container mt-5">
      <nav>
        <ul className="pagination">
          {pageNumbers.map((number) => {
            return (
              <li className="page-item" key={number}>
                <a
                  href="!#"
                  onClick={(e) => {
                    paginate(number);
                    e.preventDefault();
                  }}
                  className="page-link"
                >
                  {number}
                </a>
              </li>
            );
          })}
        </ul>
      </nav>
    </div>
  );
};

基本上,每次您单击按钮时页面都会重新渲染/刷新,并且所有数据都会丢失。这样您的页面就会恢复为默认。