javascript - Next.js:影响页面加载的 getServerSideProps 和/或 getInitialProps
问题描述
当我使用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;
解决方案
从 Next.js 的文档中,您应该data
在props
属性内返回。
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
return {
props: {
data: JSON.stringify(user, null, 2)
}
}
推荐阅读
- html - SVG 过滤器显示不正确的颜色
- macos - MacOS,在查找器中找不到时如何删除键盘快捷方式中无用的服务项目
- c++ - 移动构造函数错误并使用移动构造函数进行委派
- sql - 下次服务器重新启动时未应用 Liquibase 更改日志
- hibernate - 是否可以在单个实体中映射多行?
- php - 使用 php 中的每个循环上传 zip 档案会导致 codeigniter 中 zip 文件中的 zip 档案重复
- python - Pygame箭头键不起作用
- scala - Scala Maven 编译器:NullPointerException
- nlp - 如何编写脚本以在斯坦福依赖解析器中保留标点符号
- java - 无法使用 Java 中的动画功能更改动画图像