如何解决无法读取未定义的属性(阅读'length')?使用react、MUI和TypeScript进行分页

5n0oy7gb  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(143)

我正在开发一个代码,目的是根据JSON文件中存储的数据量,在每页上显示有限数量的卡片。我希望单击“〉”或“〈”图标将分别转到下一页或上一页,更改卡片。
我的App.tsx看起来像这样:

import { default as data } from "./DATA.json" //contains an array of json objects.

let [page, setPage] = useState(1); //is a state that stores the beginning of pagination.

const PER_PAGE = 8; //stores how many cards will be displayed per page.

const totalPages= Math.ceil(data.length / PER_PAGE); //stores the total number of pages

import { usePagination } from "./Pagination"; 
//is a component that receives as parameter data and PER_PAGE. Inside the component there are 4 functions:

currentData(); //get current data from JSON
jump(); //jump to the next page
next(); //show the contents of the next page
prev(); //show the contents of the previous page

const _DATA = usePagination(data, PER_PAGE);

Ps:在usePagination.tsx组件中,我传递了DataBooks接口的data和itemsPerPage参数,但是,出现了错误 Cannot read properties of undefined(阅读'length')。我想要的结果没有达到(当你转到下一页或上一页时相应地改变卡片),因为我不知道它是什么。有人帮帮我吗?我不知道该怎么办。

import { useState } from "react";
import Books from "./interfaces";

interface DataBooks {
  data: Books[];
  itemsPerPage: number;
}

export const usePagination = ({ data, itemsPerPage }: DataBooks) => {
  const [currentPage, setCurrentPage] = useState(1);
  const maxPage = Math.ceil(data.length / itemsPerPage);

  function currentData() {
    const begin = (currentPage - 1) * itemsPerPage;
    const end = begin + itemsPerPage;
    return data.slice(begin, end);
  }

  function next() {
    setCurrentPage((currentPage) => Math.min(currentPage + 1, maxPage));
  }

  function prev() {
    setCurrentPage((currentPage) => Math.max(currentPage - 1, 1));
  }

  function jump(page: number) {
    const pageNumber = Math.max(1, page);
    setCurrentPage((currentPage) => Math.min(pageNumber, maxPage));
  }
  return { next, prev, jump, currentData, currentPage, maxPage };
};

Code in codesanbox

u3r8eeie

u3r8eeie1#

更新

修复了项目的现场演示:codesandbox
App.tsx中,Pagination组件应如下设置:

<Pagination count={totalPages} page={page} onChange={handleChange} />

您不需要手动将eventpage传递给onChange函数,因为MUI会在内部处理它们。更具体地说,它传递给要更改到的页面而不是当前页面的函数。
这就是X1M5N11X不起作用的主要原因。我把卡的标题改为X1M6N11X,这样你就可以查看现场演示来看看它是否起作用了。

语法修正

我修正了一些语法错误,所以没有关于类型的错误消息。
UsePagination.tsx中所做的更改

// Need to check if data is provided
const maxPage = data ? Math.ceil(data.length / itemsPerPage) : 1;

function currentData() {
  // Again this data may not be provided
  if (!data) return [];

  const begin = (currentPage - 1) * itemsPerPage;
  const end = begin + itemsPerPage;
  return data.slice(begin, end);
}

App.tsx中所做的更改:

// This function take an object as argument
const _DATA = usePagination({ data, itemsPerPage: PER_PAGE });

相关问题