我想在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
重定向与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,
})
}
我将此重定向规则添加到托管网站的位置。
请改用它。 useEffect
是相当于componentDidMount的React钩子。
import { useEffect } from 'react';
import { navigate } from 'gatsby';
export default () => {
useEffect(() => {
navigate('/blog/');
}, []);
return null;
};