需要帮助在React应用中使用Redux实现分页

bvpmtnay  于 5个月前  发布在  React
关注(0)|答案(1)|浏览(73)

我目前正在使用Redux进行状态管理的React应用程序中工作。我在实现从API获取的项目列表的分页时遇到了一个挑战。
以下是我尝试的内容的简要概述:
1.已成功从API获取数据并将其存储在Redux存储中。
1.在单个页面上实现了项目的基本呈现。
然而,我正在努力找出使用Redux实现分页的最佳方法,我希望每个页面显示一定数量的项目,并提供导航以查看更多项目。
有人能指导我完成这些步骤吗?或者分享一个在React应用中使用Redux的分页实现示例?我考虑过使用react-redux-paginate这样的库,但更喜欢自定义实现,以更好地理解底层逻辑。

// Reducer
const initialState = {
  items: [],
  currentPage: 1,
  itemsPerPage: 10,
  // Other relevant state variables
};

// Actions and action creators

// Redux store setup

字符串

8gsdolmq

8gsdolmq1#

通常,结果的分页是API的一部分,
然后你只需要查询端点,给出当前的offset和每页的limit,在前端,你只需要跟踪offset
如果API不提供此功能,而是返回所有结果(多么糟糕的设计),那么您可以加载所有items,并在initialState中开始跟踪您显示的“帧”,您的操作可以是nextPageprevPage,这将操作currentPage(-=1,+=1),选择器将根据需要返回项目的数量。

const pagination = createSlice({
name: 'pagination',
initialState,
reducers: {
  clear: () => initialState,
  nextPage: (state,action) => {
    state.currentPage += 1;
    // it could be secured for going over the available pages
  },
  prevPage: (state, action) => {
    if(state.currentPage - 1 > 0) {
      state.currentPage -= 1;
    } else {
      state.currentPage = 0;
    }
  },
  // possible actions setItemsPerPage, setCurrentPage etc.
}
});

字符串
我假设pagination作为切片名称

const paginationSelector = ({ pagination }) => {  
  const { items, currentPage, itemsPerPage } = pagination;  
  const start = currentPage * itemsPerPage;

  return items.slice(start, start + itemsPerPage); 
};


组件中的某个地方

const list = useSelector(paginationSelector);

相关问题