我在typescript中有一个react组件,我想将appsync graphql查询的结果设置为state中的属性。
import React, { Component } from 'react';
import { API, graphqlOperation } from 'aws-amplify';
import {ListProjectsQuery} from './API'
import {listProjects } from './graphql/queries';
class App extends Component<{}, {
projects:ListProjectsQuery
}> {
state = {
projects: null
};
async componentDidMount() {
const projects = await API.graphql(graphqlOperation(listProjects));
this.setState({ projects });
}
...
如何定义默认状态属性以使其工作?
我发现
a similar problem
在AmplifyGitHub问题中,但该解决方案是在无状态功能组件的上下文中实现的。我使用的是有状态组件。
上面的代码抛出
Type 'null' is not assignable to type 'ListProjectsQuery'.
这是有意义的,所以我尝试在状态下映射形状,如下所示:
state = {
projects: {listProjects: {items: [{name: ''}]}}
}
所以就扔了
Types of property 'projects' are incompatible.
我要么被告知
Property does not exist on type 'Observable<object>'
最后,我尝试使用一个接口,如我发现的示例中所示:
interface IListProjectQuery {
projects: ListProjectsQuery;
}
然后我引用接口
class App extends Component<
{},
{
projects: IListProjectQuery;
}
>
它抛出以下错误
Type '{ projects: null; }' is not assignable to type 'Readonly<{ projects: IListProjectQuery; }>'.
为了让typescript高兴,我应该给默认state属性什么值?
ListProjectsQuery
导入是由amplify/appsync codegen自动生成的,类型别名如下所示:
export type ListProjectsQuery = {
listProjects: {
__typename: "ModelProjectConnection",
items: Array< {
__typename: "Project",
id: string,
name: string,
organisation: {
__typename: "Organisation",
id: string,
name: string,
} | null,
list: {
__typename: "ModelListConnection",
nextToken: string | null,
} | null,
} | null > | null,
nextToken: string | null,
} | null,
};