我想在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
答案 0 :(得分:2)
重定向与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;
};