Gatsby 中的 useLocation 挂钩和服务器端渲染错误
useLocation hook and Server Side Rendering error in Gatsby
在我的一个页面中,我想从路径中获取 page
数字参数并为此使用从 @reach/router
.[=21 导入的 useLocation
挂钩=]
import { useLocation } from '@reach/router';
路径如下所示:
http://localhost:4000/joboffers/?page=7
我从如下路径获取页码:
const pageParam = Number(useLocation().search?.split('=')[1]);
好吧,如果我 console.log
pageParam
变量,在浏览器的控制台中我得到正确的页码,但是如果我在 Visual Studio 中检查终端代码值相同变量的是 NaN
并且 Gatsby 抛出以下错误:
React Components in Gatsby must render both successfully in the
browser and in a Node.js environment. When we tried to render your
page component in Node.js, it errored.
有谁知道为什么会这样?如果我跳过 SSR,一切正常!
好吧,您完美地发现了这个问题。在SSR中(S服务器-SideRendering)window
and other global objects are not defined yet(出于显而易见的原因,您在服务器中,而不是在客户端中)因此对该变量的任何引用都将失败。
解决方案(众多可能性之一)很简单:
let pageParam;
if (typeof window !== "undefined") {
pageParam = Number(useLocation().search?.split('=')[1]);
} else {
pageParam = 0;
}
这只发生在gatsby build
期间,因为gatsby develop
命令直接在客户端运行项目(总结了很多)。
在我的一个页面中,我想从路径中获取 page
数字参数并为此使用从 @reach/router
.[=21 导入的 useLocation
挂钩=]
import { useLocation } from '@reach/router';
路径如下所示:
http://localhost:4000/joboffers/?page=7
我从如下路径获取页码:
const pageParam = Number(useLocation().search?.split('=')[1]);
好吧,如果我 console.log
pageParam
变量,在浏览器的控制台中我得到正确的页码,但是如果我在 Visual Studio 中检查终端代码值相同变量的是 NaN
并且 Gatsby 抛出以下错误:
React Components in Gatsby must render both successfully in the browser and in a Node.js environment. When we tried to render your page component in Node.js, it errored.
有谁知道为什么会这样?如果我跳过 SSR,一切正常!
好吧,您完美地发现了这个问题。在SSR中(S服务器-SideRendering)window
and other global objects are not defined yet(出于显而易见的原因,您在服务器中,而不是在客户端中)因此对该变量的任何引用都将失败。
解决方案(众多可能性之一)很简单:
let pageParam;
if (typeof window !== "undefined") {
pageParam = Number(useLocation().search?.split('=')[1]);
} else {
pageParam = 0;
}
这只发生在gatsby build
期间,因为gatsby develop
命令直接在客户端运行项目(总结了很多)。