【发布时间】:2021-09-07 23:26:56
【问题描述】:
当我使用getSeverSideProps 或getInitialProps 时,我的页面没有加载,它继续加载而不显示内容,但是当我删除这些家伙时,一切正常。我的代码有什么问题? 帮助。
...
interface Props {
data: any;
}
const Home: NextPage<Props> = ({ data }) => {
data = JSON.parse(data);
const router = useRouter();
const [showForm, setShowForm] = React.useState(false);
const theme = useSelector((state: any) => state.theme);
const className: string = `${styles.app} ${
theme === "dark" ? styles.dark__theme : styles.light__theme
}`;
return (
<div className={className}>
{/* <Header theme="light" /> */}
<HeaderSkeleton theme={theme} />
{/* <FormSkeleton theme={theme} /> */}
{showForm ? <Form theme={theme} setShowForm={setShowForm} /> : null}
<div className={styles.app__main}>
<Fleets theme={theme} />
<FleetsSkeleton theme={theme} />
<PostSkeleton theme={theme} />
<PostSkeleton theme={theme} />
<PostSkeleton theme={theme} />
<PostSkeleton theme={theme} />
<PostSkeleton theme={theme} />
<Post theme={theme} />
<Post theme={theme} />
<Post theme={theme} />
<Post theme={theme} />
</div>
<IconButton title="new post" onClick={() => setShowForm(true)}>
<IoIosCreate className={styles.home__create__post__icon} />
</IconButton>
</div>
);
};
export async function getServerSideProps(context) {
const user = await apolloClient.query({
query: USER_QUERY,
});
if (!user.data?.user) {
context.res.writeHead(307, { Location: "http://localhost:3000/welcome" });
return {
props: {
data: null,
},
};
}
return {
props: {
data: JSON.stringify(user, null, 2),
},
};
}
export default Home;
如果我使用getInitialProps,也会发生同样的情况
...
Home.getInitialProps = async (context) => {
const user = await apolloClient.query({
query: USER_QUERY,
});
if (!user.data?.user) {
context.res.writeHead(307, { Location: "http://localhost:3000/welcome" });
return {
data: null,
};
}
return {
data: JSON.stringify(user, null, 2),
};
};
export default Home;
【问题讨论】:
-
当你说它有效时,你可能是说你没有找到合适的用户?这些调用正在为您获取用户数据。如果你没有它,那么
prop带有data: null。但是,您仍然需要调试服务器 API 在服务器上失败的原因。这些调用不会被客户端调用。 -
不,我的意思是我的页面一直在刷新而不显示任何内容。但是一旦我删除 getServerSideProps 或 getInitialProps ,页面就会恢复正常。
-
@crispengari 你是否从 apollo 查询中得到了预期的数据?
-
是的,当我离开服务器加载很长时间时,我可以看到服务器上的数据。
标签: javascript reactjs typescript next.js