带有getServerSideProps的nextjs页面无法导出

时间:2020-07-23 16:15:38

标签: reactjs next.js server-side-rendering

我最近开始学习next.js并与其一起工作,我已经构建了一个简单的cpanel页面,并且每次请求该页面时它都应该获取数据(例如react的useEffect钩子),因此我尝试使用getServerSideProps,在本地开发服务器上工作正常,但是当我执行npm run dev(运行下一个构建&&下一个导出)时,它开始构建,然后在开始导出时给我这个错误:

Error occurred prerendering page "/". Read more: https://err.sh/next.js/prerender-error Error: Error for page /: pages with getServerSideProps can not be exported. See more info here: https://err.sh/next.js/gssp-export

我真的很困惑,自从最后一天以来,我一直在尝试搜索该问题,并且找不到有用的东西,现在,如果我找不到任何解决方案,我将只使用react的useEffect钩子来获取道具,但您知道getServerSideProps更好,因为它在渲染页面之前获取道具以提升页面。 这是index.js页面代码:

//  /pages/index.js

import Layout from "../components/Layout/Layout.js";
import PanelWrapper from "../components/panel/panelWrapper.js";
import getEnrolls from "../components/fetch/fetch.js";
import { API } from "../exports/config.js";

const PanelPage = ({ all, pending, accepted }) => {
  const [allEnrolls, setAllEnrolls] = React.useState(all);
  const [pendingEnrolls, setPendingEnrolls] = React.useState(pending);
  const [acceptedEnrolls, setAcceptedEnrolls] = React.useState(accepted);

  const [status, setStatus] = React.useState("all");

  const [allPage, setAllPage] = React.useState(allEnrolls.currentPage);
  const [pendingPage, setPendingPage] = React.useState(
    pendingEnrolls.currentPage
  );
  const [acceptedPage, setAcceptedPage] = React.useState(
    acceptedEnrolls.currentPage
  );

  //some functions in here
  return (
    <Layout>
      <PanelWrapper
        all={allEnrolls}
        pending={pendingEnrolls}
        accepted={acceptedEnrolls}
      />
    </Layout>
  );
};

export const getServerSideProps = async () => {
  const { all, pending, accepted } = await getEnrolls();
  return {
    props: {
      all,
      pending,
      accepted,
    },
  };
};

export default PanelPage;

1 个答案:

答案 0 :(得分:0)

请注意:不需要使用状态并在PanelPage函数中分配来自已分解的props对象的值。您的代码可以更短,更清晰。

我还对您的getServerSideProps函数做了一些小的更改。

import react, { useState } from "react";
import Layout from "../components/Layout/Layout.js";
import PanelWrapper from "../components/panel/panelWrapper.js";
import getEnrolls from "../components/fetch/fetch.js";
import { API } from "../exports/config.js";

const PanelPage = ({ all, pending, accepted }) => {
  const [status, setStatus] = useState("all");

  const [allPage, setAllPage] = useState(all.currentPage);
  const [pendingPage, setPendingPage] = useState(
    pending.currentPage
  );
  const [acceptedPage, setAcceptedPage] = useState(
    accepted.currentPage
  );

  //some functions in here
  return (
    <Layout>
      <PanelWrapper
        all={all}
        pending={pending}
        accepted={accepted}
      />
    </Layout>
  );
};

export async function getServerSideProps() {
  const res = await getEnrolls();
  const { all, pending, accepted } = await res.json();

  return {
    props: {
      all,
      pending,
      accepted,
    },
  };
};

export default PanelPage;