盖茨比重定向到主页,而不是显示404页面

问题描述 投票:3回答:3

是否有可能以某种方式将用户重定向到主页(/)而不是显示404页面?

gatsby
3个回答
2
投票

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;
}

5
投票

您可以执行以下操作:

import React from 'react'
import { Redirect } from '@reach/router'

const NotFoundPage = () => <Redirect to="/" />

export default NotFoundPage

4
投票

上面的答案将在构建时失败,因为window对象未在构建时定义。请改用它。使用效果是相当于componentDidMount的钩子。

import { useEffect } from 'react';
import { navigate } from 'gatsby';

export default () => {
  useEffect(() => {
    navigate('/your-redirect/');
  }, []);
  return null;
};

0
投票

你也可以用navigateTo()来做

import React from 'react'
import { navigateTo } from 'gatsby'

const NotFoundPage = () => {
  return navigateTo('/')
}

export default NotFoundPage
© www.soinside.com 2019 - 2024. All rights reserved.