Gatsby:当我在 URL 中传递参数时页面未呈现 [求助]?
Gatsby: page not rendering when I pass parameters in URL [Help]?
我卡在这件事上了。我想从 url 获取 url 参数 (/mypage/?title=my-title) 并将其显示在页面中。
目前我在 gatsby
中尝试了仅限客户端的路由
import path from "path"
exports.onCreatePage = ({ page, actions }) => {
const { createPage } = actions
if (page.path.match(/^\/headline\/*/)) {
createPage({
path: "/headline",
matchPath: "/headline/*",
component: path.resolve("src/templates/headline.tsx"),
})
}
}
// gatsby-node.js
这是我的模板
import React from "react"
import { Router, RouteComponentProps } from "@reach/router"
type Props = RouteComponentProps<{
title: string
}>
const Test = ({ title = "Test title", location }: Props) => {
console.log(title)
console.log(location)
return <h1>Im test</h1>
}
const Headline = () => {
console.log("handle temp called")
return (
<Router>
<Test path="/compare/headline/:title" />
</Router>
)
}
export default Headline
// src/templates/headline.tsx
当我点击 /headline/?title=test-my-app 时没有渲染
我的组件(测试)不是从 Router 标签调用的。
有帮助吗?
我认为问题很简单,您在路由器的 URL 中有一个额外的“比较”。如果您将 Router
中的部分替换为 <Test path="headline/:title" />
,它应该可以与您正在测试的 URL 一起使用。
如果路径不匹配指定的任何路径,路由器将return一个空页面。您可以添加一个 default route 作为包罗万象。
通常情况下,您不需要顺便在页面内创建路由器,但我想这取决于您的用例。
我卡在这件事上了。我想从 url 获取 url 参数 (/mypage/?title=my-title) 并将其显示在页面中。 目前我在 gatsby
中尝试了仅限客户端的路由import path from "path"
exports.onCreatePage = ({ page, actions }) => {
const { createPage } = actions
if (page.path.match(/^\/headline\/*/)) {
createPage({
path: "/headline",
matchPath: "/headline/*",
component: path.resolve("src/templates/headline.tsx"),
})
}
}
// gatsby-node.js
这是我的模板
import React from "react"
import { Router, RouteComponentProps } from "@reach/router"
type Props = RouteComponentProps<{
title: string
}>
const Test = ({ title = "Test title", location }: Props) => {
console.log(title)
console.log(location)
return <h1>Im test</h1>
}
const Headline = () => {
console.log("handle temp called")
return (
<Router>
<Test path="/compare/headline/:title" />
</Router>
)
}
export default Headline
// src/templates/headline.tsx
当我点击 /headline/?title=test-my-app 时没有渲染 我的组件(测试)不是从 Router 标签调用的。 有帮助吗?
我认为问题很简单,您在路由器的 URL 中有一个额外的“比较”。如果您将 Router
中的部分替换为 <Test path="headline/:title" />
,它应该可以与您正在测试的 URL 一起使用。
如果路径不匹配指定的任何路径,路由器将return一个空页面。您可以添加一个 default route 作为包罗万象。
通常情况下,您不需要顺便在页面内创建路由器,但我想这取决于您的用例。