首页 > 解决方案 > 当前页面的数量在反应中没有改变

问题描述

我正在使用 react-paginate ( https://www.npmjs.com/package/react-paginate ) 为我的应用程序进行分页。一切都很好,但我无法增加当前页数。因此,这是我的父组件:

import React, { useEffect, useState } from "react";
import Product from "../components/sub-components/Product";
import SimpleBox from "../components/sub-components/SimpleBox";
import BoxWithSearch from "../components/sub-components/BoxWithSearch";
import LoadingBox from "../components/sub-components/LoadingBox";
import MessageBox from "../components/sub-components/MessageBox";
import Cart from "../components/sub-components/Cart";
import { useDispatch, useSelector } from "react-redux";
import { listProducts } from "../actions/productActions";
import ReactPaginate from "react-paginate";

export default function HomeScreen() {
  const dispatch = useDispatch();
  const productList = useSelector((state) => state.productList);
  const { loading, error, products } = productList;
  const [currentPage, setCurrentPage] = useState(1);
  const [pageCount, setpageCount] = useState(0);

  useEffect(() => {
    dispatch(listProducts(currentPage));
    console.log(currentPage);
  }, [dispatch]);

  const handlePageClick = (data) => {
    setCurrentPage(data.selected + 1);
    // scroll to the top
    //window.scrollTo(0, 0)
  };
  return (
    <div className="container">
      <div className="row">
        <div className="col-lg-6 col-md-12 col-sm-12 col-xs-12">
          <h2 className="title">Products</h2>
          <div className="product-type-filter">
            <button>Mug</button>
            <button className="clicked">Shirt</button>
          </div>
          <div className="products">
            <div className="row">
              <div>
                {loading ? (
                  <LoadingBox></LoadingBox>
                ) : error ? (
                  <MessageBox variant="danger">{error}</MessageBox>
                ) : (
                  <div className="row center">
                    {products.map((product) => (
                      <Product key={product.added} product={product}></Product>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
          <ReactPaginate
            previousLabel={"Prev"}
            nextLabel={"Next"}
            pageCount={40}
            marginPagesDisplayed={4}
            pageRangeDisplayed={1}
            onPageChange={handlePageClick}
            containerClassName={"pagination justify-content-center"}
            pageClassName={"page-item"}
            pageLinkClassName={"page-link"}
            previousClassName={"page-item"}
            previousLinkClassName={"page-link"}
            nextClassName={"page-item"}
            nextLinkClassName={"page-link"}
            breakClassName={"page-item"}
            breakLinkClassName={"page-link"}
            activeClassName={"active"}
          />
        </div>
      </div>
    </div>
  );
}

以及我获取数据的操作:

import Axios from 'axios';
import {
  PRODUCT_LIST_FAIL,
  PRODUCT_LIST_REQUEST,
  PRODUCT_LIST_SUCCESS,
} from '../constants/productConstants';

export const listProducts = () => async (dispatch, currentPage) => {
  dispatch({
    type: PRODUCT_LIST_REQUEST,
  });
  try {
    const { data } = await Axios.get(`http://localhost:3000/items?_page=${currentPage}&_limit=16`);
    dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
  } catch (error) {
    dispatch({ type: PRODUCT_LIST_FAIL, payload: error.message });
  }
};

但问题是由于 currentPage 没有改变,我无法转到其他页面。您对此有解决方案吗?谢谢...

标签: reactjsreact-hookspaginationuse-effect

解决方案


如果您正在更新当前页面并想要获取新数据,那么您可能想要添加currentPageuseEffect依赖数组,以便获取/列出下一个当前页面的产品。

useEffect(() => {
  dispatch(listProducts(currentPage));
  console.log(currentPage);
}, [currentPage, dispatch]);

更新

当我在行动中写作console.log(currentPage)时,我得到了这个: ƒ getState() { var state = unliftState(liftedStore.getState()); if (state !== undefined) { lastDefinedState = state; } return lastDefinedState; }我怎样才能将currentpage数字传递给行动?

在 thunk 中,第二个参数是getState要调用并获取当前 redux 状态的函数。您的listProducts动作创建者正在命名getState回调currentPage。此外,任何传递给的参数都将listProducts被忽略(注意外部函数中的空 arg 列表)。

export const listProducts = () => async (dispatch, currentPage) => {
  dispatch({
    type: PRODUCT_LIST_REQUEST,
  });
  try {
    const { data } = await Axios.get(`http://localhost:3000/items?_page=${currentPage}&_limit=16`);
    dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
  } catch (error) {
    dispatch({ type: PRODUCT_LIST_FAIL, payload: error.message });
  }
};

listProducts需要currentPage在外部函数中使用传递的参数,并将其包含在函数范围内。

export const listProducts = (currentPage) => async (dispatch) => {
  dispatch({
    type: PRODUCT_LIST_REQUEST,
  });
  try {
    const { data } = await Axios.get(`http://localhost:3000/items?_page=${currentPage}&_limit=16`);
    dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
  } catch (error) {
    dispatch({ type: PRODUCT_LIST_FAIL, payload: error.message });
  }
};

推荐阅读