如何从索引页重定向到Gatsby.JS项目中以编程方式生成的路由

问题描述 投票:1回答:2

我想在gatsby项目中将指数/重新路由到/blog/blog路线的页面是在gatsby-node.js文件中生成的。

我尝试从Redirect导入@reach-router和返回IndexRedirect to='/blog'组件内部,但这会导致Uncaught RedirectRequest错误。

index.js文件:

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


class BlogIndex extends React.Component {
  render() {
    return (
      <Redirect to={`/blog`} />
    )
  }
}

export default BlogIndex

Error

gatsby reach-router
2个回答
2
投票

来自@reach/router docs

重定向与componentDidCatch一起使用以防止树呈现并从新位置重新开始。

因为React不会吞下错误,这可能会让您感到烦恼。例如,重定向将触发Create React App的错误覆盖。在生产中,一切都很好。如果它困扰你,请添加noThrow,重定向将在不使用componentDidCatch的情况下进行重定向。

添加一个noThrow标签似乎解决了这个问题:

<Redirect noThrow to="/topath" />

你也可以在gatsby-node.js要求盖茨比为你做这件事:

exports.createPages = ({ actions }) => {
  const { createRedirect } = actions

  createRedirect({
    fromPath: `/`,
    toPath: `/topath`,
    redirectInBrowser: true,
    isPermanent: true,
  })
}

more here


我将此重定向规则添加到托管网站的位置。


0
投票

请改用它。 useEffect是相当于componentDidMount的React钩子。

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

export default () => {
  useEffect(() => {
    navigate('/blog/');
  }, []);
  return null;
};
© www.soinside.com 2019 - 2024. All rights reserved.