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

Dak*_*ksh 7 gatsby reach-router

我想将索引重新路由//bloggatsby 项目中。/blog路由页面是在gatsby-node.js文件中生成的。

我尝试的是Redirect从返回@reach-routerIndex组件内部和内部导入,Redirect 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
Run Code Online (Sandbox Code Playgroud)

错误

Der*_*yen 10

来自@reach/router 文档

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

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

添加noThrow标签似乎可以解决这个问题:

<Redirect noThrow to="/topath" />
Run Code Online (Sandbox Code Playgroud)

你也可以要求 Gatsby 为你做这件事,在gatsby-node.js

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

  createRedirect({
    fromPath: `/`,
    toPath: `/topath`,
    redirectInBrowser: true,
    isPermanent: true,
  })
}
Run Code Online (Sandbox Code Playgroud)

在此处查看更多信息


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


Cha*_*bot 5

改用这个。的useEffect是阵营钩相当于componentDidMount。

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

export default () => {
  useEffect(() => {
    navigate('/blog/');
  }, []);
  return null;
};
Run Code Online (Sandbox Code Playgroud)