英文:
GetServerSideProps doesn't seem to be called
问题
I can help you translate the code part into Chinese. Here it is:
为什么我看不到帖子?我只能看到带有“所有帖子”的H1元素。否则什么都不会发生。在调试模式下,我也看不到调用的URL。我使用的是 Next.JS 13。如果我尝试在REACT中执行整个操作,当然不包括getServerSideProps()时,我没有问题 - 一切正常。
Main.js:
import React from "react";
export const getServerSideProps = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/posts");
let allPosts = await res.json();
return {
props: {
allPosts: allPosts.map((post) => post.title),
},
};
};
const Posts = ({ allPosts }) => {
return (
<div>
<h1>所有帖子</h1>
{allPosts?.map((post, idx) => (
<div key={idx}>{post}</div>
))}
</div>
);
};
export default Posts;
layout.jsx:
export default function RootLayout() {
return (
<html lang="en">
<head>
<title>Digital</title>
</head>
<body>
<Main></Main>
</body>
</html>
);
}
请注意,我只翻译了代码部分,不包括问题和其他内容。如果您需要更多翻译,请告诉我。
英文:
Why can't I see the posts? All I see is the H1 element with All Posts. Otherwise nothing happens. In debug mode I don't see the URL being called either. I use Next.JS 13. If I try the whole thing in REACT, without getServerSideProps() of course, I have no problem - everything works.
Main.js:
import React from "react";
export const getServerSideProps = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/posts");
let allPosts = await res.json();
return {
props: {
allPosts: allPosts.map((post) => post.title),
},
};
};
const Posts = ({ allPosts }) => {
return (
<div>
<h1>All Posts</h1>
{allPosts?.map((post, idx) => (
<div key={idx}>{post}</div>
))}
</div>
);
};
export default Posts;
layout.jsx:
export default function RootLayout() {
return (
<html lang="en">
<head>
<title>Digital</title>
</head>
<body>
<Main></Main>
</body>
</html>
);
}
答案1
得分: 0
This code worked for me, try this:
这段代码对我有效,可以尝试使用:
const Home = ({ allPosts }) => {
return (
<div>
{allPosts.map((post, index) => (
<p key={index}>
<span>{index + 1}: </span>
{post}
</p>
))}
</div>
);
};
export default Home;
export const getServerSideProps = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
let allPosts = await res.json();
return {
props: {
allPosts: allPosts.map((post) => post.title),
},
};
};
英文:
This code worked for me try this:
const Home = ({ allPosts }) => {
return (
<div>
{allPosts.map((post, index) => (
<p key={index}>
<span>{index + 1}: </span>
{post}
</p>
))}
</div>
);
};
export default Home;
export const getServerSideProps = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
let allPosts = await res.json();
return {
props: {
allPosts: allPosts.map((post) => post.title),
},
};
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论