如何在 Gatsby.JS 项目中从索引页面重定向到以编程方式生成的路由
How to redirect from the index page to a route which is generated programmatically, in a Gatsby.JS project
我想在 gatsby 项目中将索引 /
重新路由到 /blog
。 /blog
路由页面在 gatsby-node.js
文件中生成。
我尝试从 @reach-router
导入 Redirect
并在 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
Redirect works with componentDidCatch to prevent the tree from rendering and starts over with a new location.
Because React doesn’t swallow the error this might bother you. For example, a redirect will trigger Create React App’s error overlay. In production, everything is fine. If it bothers you, add noThrow and Redirect will do redirect without using componentDidCatch.
添加一个 noThrow
标签似乎可以解决这个问题:
<Redirect noThrow to="/topath" />
您也可以在 gatsby-node.js
:
中让 Gatsby 为您做这件事
exports.createPages = ({ actions }) => {
const { createRedirect } = actions
createRedirect({
fromPath: `/`,
toPath: `/topath`,
redirectInBrowser: true,
isPermanent: true,
})
}
参见more here。
我也会将此重定向规则添加到托管站点的位置。
改用这个。 useEffect
是相当于 componentDidMount 的 React 挂钩。
import { useEffect } from 'react';
import { navigate } from 'gatsby';
export default () => {
useEffect(() => {
navigate('/blog/');
}, []);
return null;
};
我想在 gatsby 项目中将索引 /
重新路由到 /blog
。 /blog
路由页面在 gatsby-node.js
文件中生成。
我尝试从 @reach-router
导入 Redirect
并在 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
Redirect works with componentDidCatch to prevent the tree from rendering and starts over with a new location.
Because React doesn’t swallow the error this might bother you. For example, a redirect will trigger Create React App’s error overlay. In production, everything is fine. If it bothers you, add noThrow and Redirect will do redirect without using 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。
我也会将此重定向规则添加到托管站点的位置。
改用这个。 useEffect
是相当于 componentDidMount 的 React 挂钩。
import { useEffect } from 'react';
import { navigate } from 'gatsby';
export default () => {
useEffect(() => {
navigate('/blog/');
}, []);
return null;
};