reactjs - 如何为 Apollo 的 React HOC 定义 props 接口(interface)?

标签 reactjs typescript react-apollo

我正在尝试使用 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)
                                    ^^^^^^^^^

如果我使用 {} 而不是接口(interface),代码会编译,但我无法在 render 函数中使用任何 props。

编辑:

我试图将最后一行重写为

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)

interface IExternalProps {
  id: string
}

interface IProps extends IExternalProps {
  data: IData
}

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

基本上,IExternalProps 是您的组件期望来自外部的 props 的接口(interface),即。当您实际在 JSX 中使用该组件时,IProps 是您通过 GraphQL 查询 (HOC) 接收的 Prop 的接口(interface)。此接口(interface)必须扩展 IExternalProps,然后 Typescript 才有机会对其进行实际类型检查。

关于reactjs - 如何为 Apollo 的 React HOC 定义 props 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44355988/

相关文章:

javascript - 正确推送到已作为 props 传递的数组

javascript - 如何使 Material UI react 按钮充当 react 路由器 DOM 链接?

angular - 如何构造一个 Angular 库以具有多个导入路径(如 @angular/material),这样做有什么好处?

typescript - 如何输入对应类型的元组数组?

graphql - 查询组件返回数据 null 但网络显示响应

apollo-server-express、apollo-server 和 apollo-cache-control 中的 TypeScript 导入问题

javascript - 基于按钮状态显示/隐藏

node.js - 在客户端和服务器 Mongoose 模型之间共享 typescript 接口(interface)

reactjs - 如何从 Apollo set Context Http Link 访问 React 上下文

带参数的 JavaScript removeEventlistener 回调