【发布时间】:2022-01-06 07:13:45
【问题描述】:
我正在使用 React、Typescript 和 Apollo 客户端。
在我的 React 组件中,我使用 useQuery 钩子 NODES_TYPE_ONE 或 NODES_TYPE_TWO 基于值 blockData.myType 进行查询。这很好用。
GraphQL 查询如下所示:
export const NODES_TYPE_ONE = gql`
query GetNodesOne($customKey: String!) {
getNodesTypeOne(customKey: $customKey) {
nodes {
id
title
}
}
}
`;
export const NODES_TYPE_TWO = gql`
query GetNodesTwo($customKey: String!) {
getNodesTypeTwo(customKey: $customKey) {
nodes {
id
title
}
}
}
`;
但是如何在GqlRes 类型中输入我的数据?
当我console.log(data); 我得到:两个不同的对象:
getNodesTypeOne {
nodes[// array of objects]
}
和
getNodesTypeTwo {
nodes[// array of objects]
}
我的GqlRes 输入:
export type GqlRes = {
getNodesTypeOne: {
nodes: NodeTeaser[];
};
};
/** @jsx jsx */
import { useQuery } from '@apollo/client';
import { jsx } from '@emotion/react';
import { Slides } from 'app/components';
import { NODES_TYPE_ONE, NODES_TYPE_TWO } from './MyBlock.gql';
import { Props, GqlRes, NodesArgs } from './MyBlock.types';
const MyBlock = ({ data: blockData, metadata }: Props) => {
const customKey = metadata.customKey;
const { data } = useQuery<GqlRes, NodesArgs>(
blockData.myType === 'type-one' ? NODES_TYPE_ONE : NODES_TYPE_TWO,
{
variables: {
customKey: metadata.customKey || 0,
},
errorPolicy: 'all',
notifyOnNetworkStatusChange: true,
ssr: false,
}
);
const items =
data?.getNodesTypeOne.nodes.map((video) => {
return {
id: video.uuid,
type: 'type-one',
title: title,
};
}) || [];
return <Slides items={items} /> : null;
};
export default MyBlock;
现在我的商品只返回getNodesTypeOne,但我如何才能同时获得它们?
更新:
我为GqlRes 创建了一个联合类型:
type GetNodeTypeOne = {
getNodesTypeOne: {
nodes: Teaser[];
};
};
type GetNodeTypeTwo = {
getNodesTypeTwo: {
nodes: Teaser[];
};
};
export type GqlRes = GetNodeTypeOne | GetNodeTypeTwo;
但是我现在如何map 节点数组呢?
更新 2
正如@Urmzd 提到的,我尝试了另一种方法。只需使用多个 useQuery 钩子:
const MyBlock = ({ data: blockData, metadata }: Props) => {
const customKey = metadata.customKey;
const { data: nodesOne } = useQuery<NodesOneGqlRes, NodesArgs>(NODES_TYPE_ONE,
{
variables: {
customKey: metadata.customKey || 0,
},
errorPolicy: 'all',
notifyOnNetworkStatusChange: true,
ssr: false,
}
);
const { data: nodesTwo } = useQuery<NodesTwoGqlRes, NodesArgs>(NODES_TYPE_TWO,
{
variables: {
customKey: metadata.customKey || 0,
},
errorPolicy: 'all',
notifyOnNetworkStatusChange: true,
ssr: false,
}
);
const items =
data?.// How do I get my nodes in a single variable?? .map((video) => {
return {
id: video.uuid,
type: 'type-one',
title: title,
};
}) || [];
return <Slides items={items} /> : null;
};
export default MyBlock;
但是我现在如何map 我的数据,因为我有两个不同的 GraphQL 响应?在这种情况下,最好的方法是什么?
【问题讨论】:
-
等等,我很困惑。为什么你有两个包含完全相同实体的实体容器?
-
另外,当有人回答您的问题时,您可能希望扩大话题,而不仅仅是编辑自己的帖子。
-
你能提供你正在做的
gql查询吗? -
@Urmzd 将查询添加到我的问题中。谢谢
-
@Urmzd 首先尝试让我的示例正常工作。我现在如何映射我的联合节点数组?
标签: reactjs typescript apollo-client