我希望你一切都好????。
在使用新的内部化 NextJS 功能时,我发现了一个我根本没有预料到的错误。
如果我传递一个纯字符串作为 prop 从getStaticProps
to the Page Component
一切正常default locale
,但是如果我传递一个对象而不是一个普通字符串,它就会中断。
我把这两个代码都留在这里。
下面的代码可以正常工作????:
- 它传递一个字符串值
- 在两种语言环境中都可以正常工作
/en
and /es
即使没有它(它选择默认区域设置)
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>
</>
);
}
下面的代码是不起作用的:
- 它传递一个对象
- 在“/en”中工作正常并且没有显式区域设置(默认区域设置),但不适用于
/es
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>
</>
);
}