我正在尝试使用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
函数中使用任何道具。
编辑:
我试图将最后一行重写为
export default graphql<any, IProps>(BrandsQuery)(BrandList)
摆脱了错误,但现在当我尝试将组件包含为
时<div>
<BrandList />
</div>
我收到以下错误:
Type '{}' is not assignable to type 'Readonly<IProps>'.
Property 'data' is missing in type '{}'.
答案 0 :(得分:1)
好的,我已经解决了这个问题..我不得不添加另一个Props接口
interface IExternalProps {
id: string
}
interface IProps extends IExternalProps {
data: IData
}
export default graphql<any, IExternalProps}>(BrandsQuery)(BrandList)
基本上,IExternalProps
是您的组件从外部期望的道具的接口,即。当您在JSX中实际使用该组件时,IProps
是您通过GraphQL查询(HOC)接收的道具的接口。此接口必须扩展IExternalProps
,Typescript然后有机会实际键入检查它。