redux 下一个数据未加载到我的分页中

rbl8hiat  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(118)

所以,我一直在使用react和redux制作一个用户目录网站。现在我想从我的本地json文件中每页分页20个用户,我得到了前20页,但是当我点击下一步按钮时,下一页没有加载。
这是我的userList.jsx:

import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setUsers } from '../store/userSlice';
import UserCard from './UserCard';
import Pagination from './Pagination';
import myData from '../data/heliverse_mock_data.json';

const UserList = () => {
  const dispatch = useDispatch();
  const users = useSelector((state) => state.users.users);
  const [currentPage, setCurrentPage] = useState(1);
  const usersPerPage = 20;
  const domainFilter = useSelector((state) => state.users.domainFilter);
  const genderFilter = useSelector((state) => state.users.genderFilter);
  const availabilityFilter = useSelector((state) => state.users.availabilityFilter);
  const searchQuery = useSelector((state) => state.users.searchQuery);

  useEffect(() => {
    dispatch(setUsers(myData));
  }, [dispatch]);

  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  

  const filteredUsers = users.filter((user) => {
    const fullName = user.first_name + user.last_name;
    let filterCondition = true;

    if (domainFilter && domainFilter !== 'All Domains' && user.domain !== domainFilter) {
      filterCondition = false;
    }
    if (genderFilter && genderFilter !== 'All Genders' && user.gender !== genderFilter) {
      filterCondition = false;
    }
    if (
      availabilityFilter &&
      availabilityFilter !== 'Both' &&
      user.available !== (availabilityFilter === 'Yes')
    ) {
      filterCondition = false;
    }
    if (searchQuery && !fullName.toLowerCase().includes(searchQuery.toLowerCase())) {
      filterCondition = false;
    }

    return filterCondition;
  });

  const totalPages = Math.ceil(filteredUsers.length / usersPerPage);
  const indexOfLastUser = currentPage * usersPerPage;
  const indexOfFirstUser = indexOfLastUser - usersPerPage;
  const currentUsers = filteredUsers.slice(indexOfFirstUser, indexOfLastUser);

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-2 gap-4 mt-8">
      {currentUsers.map((user) => (
        <UserCard key={user.id} user={user} />
      ))}
        
      <Pagination
        totalPages={totalPages}
        currentPage={currentPage}
        onPageChange={(page) => handlePageChange(page)}
      />
    </div>
  );
};

export default UserList;

这是我的分页.jsx

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setPaginationPage } from '../store/userSlice';

const Pagination = () => {
  const dispatch = useDispatch();
  const currentPage = useSelector((state) => state.users.paginationPage);
  const totalPages = useSelector((state) => state.users.totalPages);

  const handlePageChange = (page) => {
    dispatch(setPaginationPage(page));
  };

  const handleNextPage = () => {
    if (currentPage < totalPages) {
      handlePageChange(currentPage + 1);
      console.log("h")
    }
  };

  const handlePreviousPage = () => {
    if (currentPage > 1) {
      handlePageChange(currentPage - 1);
    }
  };

  const renderPaginationLinks = () => {
    const links = [];
    for (let i = 1; i <= totalPages; i++) {
      links.push(
        <button
          key={i}
          className={`px-4 py-2 rounded-md ${
            i === currentPage ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800'
          }`}
          onClick={() => handlePageChange(i)}
        >
          {i}
        </button>
      );
    }
    return links;
  };

  return (
    <div className="flex items-center">
      <button
        onClick={handlePreviousPage}
        disabled={currentPage === 1}
        className={`px-4 py-2 rounded-md mr-2 ${
          currentPage === 1 ? 'bg-gray-300 cursor-not-allowed' : 'bg-blue-500 text-white'
        }`}
      >
        Previous
      </button>
      {renderPaginationLinks()}
      <button
        onClick={handleNextPage}
        disabled={currentPage === totalPages}
        className={`px-4 py-2 rounded-md ml-2 ${
          currentPage === totalPages ? 'bg-gray-300 cursor-not-allowed' : 'bg-blue-500 text-white'
        }`}
      >
        Next
      </button>
    </div>
  );
};

export default Pagination;

这是我的redux商店userSlice.jsx

import { configureStore, createSlice } from '@reduxjs/toolkit';

const initialState = {
    users: [],
    searchQuery: '',
    domainFilter: '',
    genderFilter: '',
    availabilityFilter: '',
    paginationPage: 1,
    teamMembers: [],
    totalPages:26
};


const userSlice = createSlice({
    name: 'users',
    initialState,
    reducers: {
        setUsers: (state, action) => {
            state.users = action.payload;
        },
        setSearchQuery: (state, action) => {
            state.searchQuery = action.payload
        },
        setDomainFilter: (state, action) => {
            state.domainFilter = action.payload
        },
        setGenderFilter: (state, action) => {
            state.genderFilter = action.payload;
        },
        setAvailabilityFilter: (state, action) => {
            state.availabilityFilter = action.payload
        },
        setPaginationPage: (state, action) => {
            state.paginationPage = action.payload
        },
        addToTeam: (state, action) => {
            state.teamMembers.push(action.payload)
        },
        removeFromTeam: (state, action) => {
            state.teamMembers = state.teamMembers.filter(
                (user) => user.id !== action.payload
            )
        }
    },
    
})


const store = configureStore({
    reducer: {
        users: userSlice.reducer
    },
});

export const { setUsers, setSearchQuery, setDomainFilter, setGenderFilter, setAvailabilityFilter, setPaginationPage , addToTeam , removeFromTeam} = userSlice.actions

export default store;

我试着在pagation.jsx中记录handleNextPage,以为currentPage或totalPages中可能有问题,但事实并非如此。

l3zydbqr

l3zydbqr1#

看起来您在两个地方管理当前页面状态:一次是在UserList组件中,另一次是在Redux商店中。这可能是导致问题的原因。
当您单击下一步按钮时,您正在更新Redux商店中的paginationPage,但UserList组件中的currentPage保持不变,因此您看到的用户是相同的。
我有个建议为什么不从UserList组件中删除本地currentPage状态,而使用Redux存储中的paginationPage?您可以通过将const [currentPage, setCurrentPage] = useState(1);替换为const currentPage = useSelector((state) => state.users.paginationPage)来实现这一点;在UserList组件中。
handlePageChange函数中,您可以分派setPaginationPage操作,而不是设置本地状态。这样,UserList和Pagination组件将在Redux存储中使用和更新相同的状态,并且您的分页应该可以正常工作。

相关问题