我正在关注next.js的YouTube教程,因此我刚开始就陷入了困境。我正在尝试使用以下代码为我的网站创建动态内容和路由,但是出现错误:
import Link from 'next/Link';
const people = [
{v: 'car', name: 'bruno'},
{v: 'bike', name: 'john'},
{v: 'airplane', name: 'mick'}
]
export default function Details (){
return <div>
{people.map( e => (
<div>
<Link as={'/${e.v}/${e.name}'} href="/[vehicle]/[person]">
<a>Navigate to {e.name}'s {e.v}</a>
</Link>
</div>
))}
</div>
}
上面代码的动态路由实际上运行良好。但是当我转到详细信息页面时,内容看起来像“ $ {e.name}的$ {e.v}”。根据我的参数,它看起来不像。我相信问题是由于以下原因引起的:
<Link as={'/${e.v}/${e.name}'} href="/[vehicle]/[person]">
我试图将“”这个引号改为“”反引号,但这也不起作用。你能帮我吗?
我在开发人员工具控制台中也收到此错误。我出于某种目的更改了fb.me链接。
Warning: Each child in a list should have a unique "key" prop.
Check the top-level render call using <div>. See blablafb.me/react-warning-keys for more information.
in Link (at Details.js:13)
in Details
in App
in Unknown
in Context.Provider
in Context.Provider
in Context.Provider
in Context.Provider
in AppContainer
答案 0 :(得分:0)
在您的/pages/index.js
文件中,您可以将单引号'和反引号`更改为允许字符串插值,并在顶层key
上添加一个div
属性,您可以在此映射人的数组:
import Link from "next/link";
const people = [
{ v: "car", name: "bruno" },
{ v: "bike", name: "john" },
{ v: "airplane", name: "mick" }
];
export default function Details() {
return (
<div>
{people.map((e, idx) => (
<div key={idx}>
<Link href="/[vehicle]/[person]" as={`/${e.v}/${e.name}`} passHref>
<a>
Navigate to {e.name}'s {e.v}
</a>
</Link>
</div>
))}
</div>
);
}
然后创建/pages/[vehicle]/[person].js
,在其中根据您单击的链接显示不同的内容:
import { useRouter } from "next/router";
import Link from "next/link";
export default function Person() {
const router = useRouter();
const { vehicle, person } = router.query;
return (
<div>
<p>
Vehicle: {vehicle}, Person: {person}
</p>
Go back{" "}
<Link href="/" passHref>
<a>Home</a>
</Link>
</div>
);
}