所有预加载的链接的Next.js 404错误

JavaScript React.js

村村番长

2020-03-24

I'm new to next.js and as a first step, before I start developing the actual app, I'm following the docs to learn the basics, and right now, I'm struggled trying to get the prefetch working, since all the preloaded requests are returning 404 error.

So what's wrong with my code? How can I solve this problem?

The demo repository is on github.

在此处输入图片说明

第3471篇《所有预加载的链接的Next.js 404错误》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
宝儿 2020.03.24

请注意,只有express服务器知道如何处理此类URL /post/:idnext.js但不知道,因此会next.js尝试预取不存在的页面(您可能会在Chrome控制台输出中看到)。

您可以轻松地解决此问题:只需以这种方式重写链接

<Link href={`/post/?id=${show.id}`} as={`/post/${show.id}`} prefetch>

结果,post.js将仅执行一个查询以预取页面。 在此处输入图片说明

这种技术称为“路由屏蔽”,您可以在Next.js教程中了解更多信息。

An update: It seems that the question is more about how prefetch feature actually works in Next.js so I will try to explain it. Without prefetch prop on the Link Next.js will load related chunk on demand (when a user clicks link) so it will cause a small delay to load and parse javascript. The prefetch prop allows you to remove this delay because javascript will be loaded as soon as possible after application start. In both cases new page will be rendered in the browser like in a usual React app.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android