如何修复“TypeError:Cannot read properties of undefined(阅读'length')”in nextjs?

qv7cva1a  于 2023-04-20  发布在  其他
关注(0)|答案(1)|浏览(318)

enter image description here我猜getStaticProps不太好用,但我不知道确切的.. getStaticProps是在render Main函数之后render的吗?
下面的代码是index.js

import Main from "../components/main/main";

export default function Home() {
  return <Main/>;
}

下面的代码是main.js

export async function getStaticProps() {
  const files = fs.readdirSync("ContentDetail");

  const getposts = files.map((fileName) => {
    const slug = fileName.replace(".md", "");
    const readFile = fs.readFileSync(`ContentDetail/${fileName}`, "utf-8");
    const { data: info, content } = matter(readFile);
    return {
      info,
      slug,
    };
  });

  return {
    props: {
      getposts,
    },
  };
}

export default function Main({ getposts }) {
  const [posts, setPosts] = useState(getposts);
  const [groupstyle, setGroupstyle] = useState();
  const [pages, setPages] = useState([]);
  const [totalPages, setTotalPages] = useState(Math.ceil(posts.length / 7));
  const [itemOffset, setItemOffset] = useState(0);

  const currentItems = posts.slice(itemOffset, itemOffset + 7);

  const contentRef = useRef([]);
  const backRef = useRef(null);
  ......
fiei3ece

fiei3ece1#

更改以下行:

const [totalPages, setTotalPages] = useState(Math.ceil(posts && posts.length / 7));

相关问题