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

时间:2019-02-25 16:18:19

标签: gatsby reach-router

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

我尝试从Redirect导入@reach-router并在Index组件内返回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

Error

2 个答案:

答案 0 :(得分: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


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

答案 1 :(得分:0)

改为使用它。 useEffect是与componentDidMount等效的React钩子。

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

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