reactjs - 使用 React 和 TS 将 PageProps 从 Gatsby 和 Parent 传递到功能组件返回未定义

标签 reactjs typescript gatsby

我有以下功能组件。我正在尝试从 Gatsby 的“Pageprops”访问 Prop 以及从我的 parent 那里访问 Prop 。我的“数据”和“错误”正在从父级返回。

返回“数据”和“错误”未定义,但返回正确的“路径”:

import { graphql, PageProps } from 'gatsby'

...
const Events = ({ path }: PageProps, { data, errors }) => {

这会正确返回数据和错误,但我无权访问 Gatsby pageProps:

...
const Events = ({ data, errors }) => {

最佳答案

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>
    </>
  )
}

就您而言,您正在子元素(dataerrorpath)中解构您的 props 。因此,要访问完整的 pageProps 您只需要:

...
const Events = (props: PageProps) => {
   const { error, data, path } = PageProps
   ... 
}

注意:如果需要,请添加所需的接口(interface)。

这样,您仍然可以解构 props 并继续访问 PageProps

关于reactjs - 使用 React 和 TS 将 PageProps 从 Gatsby 和 Parent 传递到功能组件返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65511448/

相关文章:

javascript - 根据环境响应不同的主页最佳实践

javascript - 存储可重用的 React+Flux 表单组件(一个组件用于具有不同字段的多个表单)

reactjs - React with TypeScript - 类型 {...} 不可分配给类型 'Readonly<S>'

javascript - React - 从数组中删除项目而不是重新渲染列表

asp.net-mvc - Visual Studio 中使用 TypeScript 的 lib.d.ts 中出现 100 多个错误

javascript - GatsbyJS 和 Contentful : data coming up undefined

javascript - React 中的多个 API 调用

javascript - 使用 Mongoose 模式将多个选择元素值的值存储到 MongoDB 中的数组中

reactjs - 无法运行 gatsby develop - 加载本地开发命令时出现问题

javascript - 如何使用 Gatsby 在 Netlify 上获取多步骤表单