如何修复 window 未在 gatsby 中定义
how to fix window is not defined in gatsby
我正在使用 Gatsby 制作应用程序,但我遇到了这个错误:
SSR 路径时出现意外错误:/
ReferenceError: window 未定义。
const activeIndex = () => {
const found = routes.indexOf(
routes.filter(
({ node: { name, link } }) =>
(link || `/${name.toLowerCase()}`) === window.location.pathname
)[0]
)
return found === -1 ? false : found
}
错误来自这些代码。谢谢
正如你在docs中所看到的,你只需要添加以下条件:
typeof window !== "undefined"
应用于您的代码:
const activeIndex = () => {
if(typeof window != "undefined"){
const found = routes.indexOf(
routes.filter(
({ node: { name, link } }) =>
(link || `/${name.toLowerCase()}`) === window.location.pathname
)[0]
)
return found === -1 ? false : found
}
}
我正在使用 Gatsby 制作应用程序,但我遇到了这个错误:
SSR 路径时出现意外错误:/ ReferenceError: window 未定义。
const activeIndex = () => {
const found = routes.indexOf(
routes.filter(
({ node: { name, link } }) =>
(link || `/${name.toLowerCase()}`) === window.location.pathname
)[0]
)
return found === -1 ? false : found
}
错误来自这些代码。谢谢
正如你在docs中所看到的,你只需要添加以下条件:
typeof window !== "undefined"
应用于您的代码:
const activeIndex = () => {
if(typeof window != "undefined"){
const found = routes.indexOf(
routes.filter(
({ node: { name, link } }) =>
(link || `/${name.toLowerCase()}`) === window.location.pathname
)[0]
)
return found === -1 ? false : found
}
}