英文:
How to fix "TypeError: Cannot read properties of undefined (reading 'length')" in nextjs?
问题
I guess getStaticProps doesn't work well, but I don't know exact..
Is getStaticProps render after render Main function?
以下代码是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);
// ...
}
英文:
enter image description here
I guess getStaticProps doesn't work well, but I don't know exact..
Is getStaticProps render after render Main function?
below code is index.js
import Main from "../components/main/main";
export default function Home() {
return <Main/>;
}
below code is 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);
......
答案1
得分: 0
修改以下行:
const [totalPages, setTotalPages] = useState(Math.ceil(posts && posts.length / 7));
英文:
Change the following line:
const [totalPages, setTotalPages] = useState(Math.ceil(posts && posts.length / 7));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论