Javascript 用户配置文件URL的Gatsby动态路由
我想在pages/index.js和gatsby-node.js文件中设置路由器,通过动态链接显示用户配置文件。 用户配置文件应具有如下URL:https://domain/user_name. 当我访问这个URL时,它应该显示一个UserPublicProfile组件,现在它显示404页面,其中有一个不存在的页面。此外,我还有一个/app/page,它将路由到其他底层应用程序组件。https://domain/app/ 不应作为配置文件URL路由,每隔一个URLhttps://domain/ 只是配置文件URL 我可以创建一个额外的页面用户配置文件,然后使用URL,如https://domain/user-profile/user_name. 但我需要有上述形式的网址 gatsby-node.js pages/index.js:Javascript 用户配置文件URL的Gatsby动态路由,javascript,reactjs,routes,gatsby,router,Javascript,Reactjs,Routes,Gatsby,Router,我想在pages/index.js和gatsby-node.js文件中设置路由器,通过动态链接显示用户配置文件。 用户配置文件应具有如下URL:https://domain/user_name. 当我访问这个URL时,它应该显示一个UserPublicProfile组件,现在它显示404页面,其中有一个不存在的页面。此外,我还有一个/app/page,它将路由到其他底层应用程序组件。https://domain/app/ 不应作为配置文件URL路由,每隔一个URLhttps://domain/
从“@reach/Router”导入{Router};
我通过在gatsby-node.js中使用createPages函数找到了一个解决方案
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
if (page.path.match(/^\/app/)) {
page.matchPath = "/app/*"
createPage(page)
}
else if (page.path.match(/^\/(?!app).*/)) {
page.matchPath = "/:id"
createPage(page)
}
else if (page.path.match(/^\/user-profile/)) {
page.matchPath = "/user-profile/:id"
createPage(page)
}}
import { Router } from "@reach/router";
<Router basepath="/">
<PrivateRoute path="/user-profile" component={UserPublicProfile} />
<PrivateRoute path="/" component={UserPublicProfile} />
</Router>
exports.createPages = async ({ actions: { createPage } }) => {
// get all users to crete them a profile page
axios
.get(process.env.API_DOMAIN + "/getAllUsersPublicProfiles")
.then(result => {
var users = result.data.data;
users.forEach((user) => {
createPage({
path: `/${user.link_tag}/`,
component: require.resolve(
"./src/components/userPublicProfile/userPublicProfile.js"
),
context: { user: user },
});
});
})
.catch((e) => {
console.log("Failed to load users data: " + e);
});
};