如何为 Apollo 的 React HOC 定义 props 接口?

2024-06-06

我正在尝试使用 Apollo 的 React HOC 来获取数据并将其传递给我的组件,但出现以下错误:

Argument of type 'typeof BrandList' is not assignable to parameter of type 
'CompositeComponent<{ data?: QueryProps | undefined; mutate?: MutationFunc<{}> | undefined; }>'.
Type 'typeof BrandList' is not assignable to type 'StatelessComponent<{ data?: 
QueryProps | undefined; mutate?: MutationFunc<{}> | undefined; }>'.
Type 'typeof BrandList' provides no match for the signature '(props: { data?: 
QueryProps | undefined; mutate?: MutationFunc<{}> | undefined; } & { children?: ReactNode; }, context?: any): ReactElement<any>'.

我的文件如下所示:

import * as React from 'react'
import {graphql} from 'react-apollo'
import gql from 'graphql-tag'

const BrandsQuery = gql`
  query {
    allBrands {
      id
      name
    }
  }
`

interface IBrand {
  id: string
  name: string
}

interface IData {
  loading: boolean,
  allBrands: IBrand[]
}

interface IProps {
  data: IData
}

class BrandList extends React.Component<IProps, void> {
  public render () {
    const {loading, allBrands} = this.props.data

    if (loading) {
      return (
        <div>Loading data..</div>
      )
    }

    return (
      <div>
        {allBrands.map((brand) => (
          <li>{brand.id} - {brand.name}</li>
        ))}
      </div>
    )
  }
}

export default graphql(BrandsQuery)(BrandList)
                                    ^^^^^^^^^

如果我使用{}代码编译而不是接口,但是我不能在里面使用任何道具render功能。

EDIT:

我尝试将最后一行重写为

export default graphql<any, IProps>(BrandsQuery)(BrandList)

这消除了错误,但是现在当我尝试将组件包含为

<div>
    <BrandList />
</div>

我收到以下错误:

Type '{}' is not assignable to type 'Readonly<IProps>'.
Property 'data' is missing in type '{}'.

好吧,我已经解决了这样的问题..我必须添加另一个 Props 接口

interface IExternalProps {
  id: string
}

interface IProps extends IExternalProps {
  data: IData
}

export default graphql<any, IExternalProps}>(BrandsQuery)(BrandList)

基本上,IExternalProps是您的组件期望从外部获得的道具的接口,即。当你实际在 JSX 中使用该组件时,同时IProps是您通过 GraphQL 查询 (HOC) 接收的 props 的接口。该接口必须扩展IExternalProps,Typescript 然后就有机会实际进行类型检查。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 Apollo 的 React HOC 定义 props 接口? 的相关文章

随机推荐