Nextjs getStaticProps 将对象作为 prop 而不是纯字符串传递时出错

Nextjs getStaticProps error when passing an object as prop instead of plain string

希望你一切顺利。

尝试使用新的内部化 NextJS 功能时,我发现了一个完全没有预料到的错误。

如果我将一个纯字符串作为 prop 从 getStaticProps 传递到 Page Component,在 default locale 中一切正常,但如果我传递一个对象它不是纯字符串,而是中断。

我把这两个代码都留在这里。

以下代码运行良好:

import { useRouter } from "next/dist/client/router";

export async function getStaticPaths() {
  return {
    paths: [
      { params: { name: `victor`, locale: "es" } },
      { params: { name: `victor`, locale: "en" } },
    ],
    fallback: true,
  };
}

export async function getStaticProps(context) {
  const { params } = context;
  const { name } = params;

  return {
    props: {
      name,
    },
  };
}

/*
 * ✅ The following URLs work
 * - localhost:3000/victor
 * - localhost:3000/en/victor
 * - localhost:3000/es/victor
 *
 * TypeError: Cannot destructure property 'name' of 'person' as it is undefined.
 */
export default function PageComponent({ name }) {
  const router = useRouter();
  return (
    <>
      <div>The name is: {name}</div>
      <div>Locale used /{router.locale}/</div>
    </>
  );
}

以下代码无效:

import { useRouter } from "next/dist/client/router";

export async function getStaticPaths() {
  return {
    paths: [
      { params: { name: `victor`, locale: "es" } },
      { params: { name: `victor`, locale: "en" } },
    ],
    fallback: true,
  };
}

export async function getStaticProps(context) {
  const { params } = context;
  const { name } = params;

  return {
    props: {
      person: {
        name,
      },
    },
  };
}

/*
 * ✅ The following URLs work
 * - localhost:3000/victor
 * - localhost:3000/en/victor
 *
 *  The following URLs DOESN'T work
 * - localhost:3000/es/victor
 *
 * TypeError: Cannot destructure property 'name' of 'person' as it is undefined.
 */
export default function PageComponent(props) {
  const router = useRouter();
  const { person } = props;
  const { name } = person;
  return (
    <>
      <div>The name is: {name}</div>
      <div>Locale used /{router.locale}/</div>
    </>
  );
}

因为你使用的是fallback: true.

页面在数据准备好之前渲染,你需要在你的组件中使用router.isFallback标志来处理这种情况:

  if (router.isFallback) {
    return <div>Loading...</div>
  }

或者您可以使用 fallback: 'blocking' 让 Next.js 在呈现页面之前等待数据。

More info in the docs