reactjs - 在使用 React 和 TS 时,将 PageProps 从 Gatsby 和父组件传递到函数组件返回 undefined
我有以下的函数组件。我正在尝试在 Gatsby 中访问来自 'Pageprops' 的 props,同时也访问来自父组件的 props。我从父组件返回了 'data' 和 'errors'。
对于 'data' 和 'errors' 返回未定义,但返回正确的 'path':
import { graphql, PageProps } from 'gatsby'
...
const Events = ({ path }: PageProps, { data, errors }) => {
这会正确返回数据和错误,但我无法访问 Gatsby 的 pageProps:
...
const Events = ({ data, errors }) => {
答案#1
PageProps 是一种声明式方式,结合 Gatsby 和 TypeScript 来访问 props。例如:
import React from "react"
import { PageProps } from "gatsby"
export default function IndexRoute(props: PageProps) {
return (
<>
<h1>Path:</h1>
<p>{props.path}</p>
</>
)
}
在你的情况下,你正在对子元素(data、error 和 path)的 props 进行解构。因此,要访问完整的 pageProps,你只需:
...
const Events = (props: PageProps) => {
const { error, data, path } = PageProps
...
}
注意:如有需要,请添加所需的接口。
通过这种方式,你仍然可以解构你的 props 并继续访问 PageProps。
答案#2
你正在将 {data, errors} 声明为你的函数组件的第二个参数,但你只接收一个参数,这个参数应该是 props,这就是你得到 undefined 的原因。你可以创建一个接口来声明类型,并按如下方式传递:
interface EventsProps {
data: any; // define type for data
errors: any; // define type for errors
}
const Events = ({ path, data, errors }: EventsProps & PageProps) => {
