gpt4 book ai didi

reactjs - 如何在 React 中为 AWS amplify GraphQL 响应设置 typescript 类型?

转载 作者:行者123 更新时间:2023-12-02 14:53:04 26 4
gpt4 key购买 nike

我在 typescript 中有一个 react 组件,我想将 appsync graphql 查询的结果设置为状态中的属性。

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在放大 github 问题中,但该解决方案是在无状态功能组件的上下文中。我正在使用有状态组件。

根据我的尝试,我似乎遇到了三个错误之一。

上面的代码抛出 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;
}

然后我引用接口(interface)

class App extends Component<
{},
{
projects: IListProjectQuery;
}
>

并抛出以下错误 Type '{ projects: null; }' is not assignable to type 'Readonly<{ projects: IListProjectQuery; }>'.

我应该为默认状态属性赋予什么值才能使 typescript 满意?

ListProjectsQuery import 由 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,
};

最佳答案

  • 你必须定义一个类型来匹配你期望从放大中得到的数据结构
  • 第二步是将您的响应数据转换为您定义的类型,仅此而已。
  • 您所在州的项目属性应该正确输入,项目:IProject[] |未定义 。您要么有一系列项目,要么未定义。

export type IProject = {
name: string
}

export type GetProjectsQuery = {
listProjects:{
items: IProject[]
nextToken: string
}
}

const fetchAllProjects = async () => {
try {
const result = (await API.graphql(graphqlOperation(queries.listProjects))) as {
data: GetProjectsQuery
}
projects = result.data.listProjects.items


} catch (error) {
//handle error here
}

关于reactjs - 如何在 React 中为 AWS amplify GraphQL 响应设置 typescript 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com