试图将我下面的状态 sortNew 传递给Apollo查询中的变量,但出现以下400错误:
错误:网络错误:响应失败:收到状态码400
更新: 错误详情如下:
[GraphQL错误]:消息:类型为“字符串!”的变量“ $ orderBy”用于期望类型为“ ItemOrderByInput”的位置。,位置:[对象对象],[对象对象],路径:未定义
这是我正在使用的当前代码,这会给我带来错误。
尝试获取 ALL_ITEMS_QUERY 以采用 orderBy 变量。我想念什么吗?
import React, { Component } from "react";
import { Query } from "react-apollo";
import gql from "graphql-tag";
import styled from "styled-components";
import Item from "./Item";
import Pagination from "./Pagination";
import { perPage } from "../config";
import Sort from "./Sort";
const ALL_ITEMS_QUERY = gql`
query ALL_ITEMS_QUERY($skip: Int = 0, $first: Int = ${perPage}, $orderBy: String!) {
items(first: $first, skip: $skip, orderBy: $orderBy) {
id
title
price
description
image
largeImage
}
}
`;
const Center = styled.div`
text-align: center;
`;
const ItemsList = styled.div`
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 60px;
max-width: ${props => props.theme.maxWidth};
margin: 0 auto;
padding-bottom: 80px;
`;
class Items extends Component {
state = {
sortNew: "createdAt_ASC"
};
render() {
return (
<Center>
<Pagination page={this.props.page} />
<Sort />
<Query
query={ALL_ITEMS_QUERY}
variables={{
orderBy: this.state.sortNew,
skip: this.props.page * perPage - perPage
}}
>
{({ data, error, loading }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ItemsList>
{data.items.map(item => (
<Item item={item} key={item.id} />
))}
</ItemsList>
);
}}
</Query>
<Pagination page={this.props.page} />
</Center>
);
}
}
export default Items;
答案 0 :(得分:1)
ALL_ITEMS_QUERY期望orderBy是一个像orderBy: createdAt_ASC
这样的枚举,但是您正在传递字符串orderBy: String!
。要解决此问题,请将枚举名称传递给ALL_ITEMS_QUERY
,这样可以动态更改orderBy。
一个例子看起来像这样
const ALL_ITEMS_QUERY = gql`
query ALL_ITEMS_QUERY($skip: Int = 0, $first: Int = ${perPage}, $orderBy: NameOfItemsEnum) {
items(first: $first, skip: $skip, orderBy: $orderBy) {
id
title
price
description
image
largeImage
}
}
`;
其中NameOfItemsEnum
是在后端为枚举类型指定的名称