【发布时间】:2019-02-09 06:58:14
【问题描述】:
我在 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 });
}
...
如何定义默认状态属性以使其工作?
我在放大 github 问题中找到了 a similar problem,但该解决方案是在无状态功能组件的上下文中。我正在使用有状态组件。
根据我的尝试,我似乎遇到了三个错误之一。
上面的代码抛出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 满意?
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,
};
【问题讨论】:
标签: reactjs typescript amazon-web-services aws-appsync aws-amplify