本文介绍了所有预加载链接的 Next.js 404 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 next.js 的新手,作为第一步,在我开始开发实际应用程序之前,我会按照文档来学习基础知识,而现在,我正在努力让预取正常工作,因为所有预加载的请求都返回 404 错误.

那么我的代码有什么问题?我该如何解决这个问题?

演示库位于

解决方案

注意只有express服务器知道如何处理这种/post/:id的URL,next.js 不知道,所以 next.js 会尝试预取不存在的页面(您可能会在 Chrome 控制台输出中看到).

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

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

因此,只会执行一个预取 post.js 页面的查询.

这种技术称为路由屏蔽",您可以在 Next.js 教程

更新:似乎问题更多的是关于 prefetch 功能在 Next.js 中的实际工作方式,所以我将尝试解释它.如果 Link Next.js 上没有 prefetch 属性,它将按需加载相关块(当用户单击链接时),因此会导致加载和解析 javascript 的一小段延迟.prefetch 属性允许您消除此延迟,因为 javascript 将在应用程序启动后尽快加载.在这两种情况下,新页面都将在浏览器中呈现,就像在通常的 React 应用程序中一样.

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.

解决方案

Notice that only express server knows how to process URL of this kind /post/:id, next.js doesn't know it so next.js tries to prefetch unexistent pages (and you may see in the Chrome console output).

You may fix this behaviour easily: just need rewrite your links this way

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

As a result only one query to prefetch post.js page will be executed.

This technique is called "route masking" you may read more about in in the Next.js tutorial

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.

这篇关于所有预加载链接的 Next.js 404 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 03:28