是否有可能以某种方式将用户重定向到主页(/
)而不是显示404页面?
Gatsby从src/pages/404.jsx
创建404页面(如果你没有使用404.js
扩展,则为jsx
)。因此,创建一个重定向到主页的组件应该有技巧,如下所示:
import React from 'react';
export default function NotFound() {
if (typeof window !== 'undefined') {
window.location = '/';
}
return null;
}
您可以执行以下操作:
import React from 'react'
import { Redirect } from '@reach/router'
const NotFoundPage = () => <Redirect to="/" />
export default NotFoundPage
上面的答案将在构建时失败,因为window
对象未在构建时定义。请改用它。使用效果是相当于componentDidMount
的钩子。
import { useEffect } from 'react';
import { navigate } from 'gatsby';
export default () => {
useEffect(() => {
navigate('/your-redirect/');
}, []);
return null;
};
你也可以用navigateTo()
来做
import React from 'react'
import { navigateTo } from 'gatsby'
const NotFoundPage = () => {
return navigateTo('/')
}
export default NotFoundPage