首页 > 解决方案 > Next.js:影响页面加载的 getServerSideProps 和/或 getInitialProps

问题描述

当我使用getSeverSidePropsgetInitialProps我的页面未加载时,它会继续加载而不显示内容,但是当我删除这些家伙时,一切正常。我的代码有什么问题?帮助

...
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;

标签: javascriptreactjstypescriptnext.js

解决方案


从 Next.js 的文档中,您应该dataprops属性内返回。
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering

return {
  props: {
    data: JSON.stringify(user, null, 2)
  }
}

推荐阅读