盖茨比:如何解决tslint期望组件在查询到组件本身时会收到道具

时间:2019-01-21 11:13:31

标签: javascript typescript gatsby contentful

我将Gatsby与Typescript结合使用,以基于Contentful CMS创建博客。

我有FeaturedPost组件要在主页上放置,这是代码:

FeaturedPost.tsx

interface IProps {
  data: {
    contentfulPost: ContentfulPost;
  };
}

const FeaturedPost: React.FunctionComponent<IProps> = ({ data }) => {
  const { title, description } = data.contentfulPost;
  return (
    <>
      <Header>{title}</Header>;
      <div>{description}</div>
    </>
  );
};

export const query = graphql`
  query featuredPost($slug: String) {
    contentfulPost(slug: { eq: $slug }) {
      title
      slug
      description {
        childMarkdownRemark {
          html
        }
      }
    }
  }
`;

export default FeaturedPost;

这是我的索引页代码:

index.tsx

const IndexPage: React.FunctionComponent<P> = () => {
  return (
    <Layout>
      <SEO
        title="Home"
        keywords={[`gatsby`, `application`, `react`]}
        description="Index for something I can't remember?!"
      />
      <FeaturedPost />
      <h1>Hi people</h1>
      <p>Welcome to your new Gatsby site.</p>
      <p>Now go build something great.</p>
      <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }} />
    </Layout>
  );
};

export default IndexPage;

Tslint现在期望我在data上实现FeaturedPost时将一个名为interface IProps的prop传递给FeaturedPost组件,但是实际上没有data通过。

FeaturedPost本身从发送的查询中接收它作为响应。您是否知道这段代码出了什么问题或我如何满足lint的要求?

1 个答案:

答案 0 :(得分:1)

在Gatsby v2中,非页面组件中的graphql查询将被忽略。 Use StaticQuery instead。这是一个小例子:

import * as React from 'react'
import { StaticQuery, graphql, Link } from 'gatsby'

type TOCDataType = {
  readonly allSitePage: {
    edges: [
      {
        node: {
          id: string
          path: string
        }
      }
    ]
  }
}

const TableOfContents: React.FunctionComponent<{}> = () => (
  <StaticQuery
    query={graphql`
      query SitePageQuery {
        allSitePage {
          edges {
            node {
              id
              path
            }
          }
        }
      }
    `}
    render={(data: TOCDataType) => (
      <div>
        {data.allSitePage.edges.map(({ node }) => (
          <li key={node.id}>
            <Link to={node.path}>{node.path}</Link>
          </li>
        ))}
      </div>
    )}
  />
)

export default TableOfContents