Javascript 使用模板文字类型${}的GraphQL变异
我目前有Graphql突变的问题。硬编码更新元素有效,但我传入参数的选项2无效。 在GoogleDevTools网络上,我看到我正在将[object]作为元素请求传递 我尝试更改为下面的代码,这导致键入任何错误和重复标识符args错误Javascript 使用模板文字类型${}的GraphQL变异,javascript,typescript,axios,graphql,template-literals,Javascript,Typescript,Axios,Graphql,Template Literals,我目前有Graphql突变的问题。硬编码更新元素有效,但我传入参数的选项2无效。 在GoogleDevTools网络上,我看到我正在将[object]作为元素请求传递 我尝试更改为下面的代码,这导致键入任何错误和重复标识符args错误 `{args.elements}` 任何提示,谢谢。 另外,我没有使用变量,因为api似乎不接受它们 api.ts方案1:工程 export const mutateReq = (args: TW): AxiosPromise<TW[]> =>
`{args.elements}`
任何提示,谢谢。
另外,我没有使用变量,因为api似乎不接受它们
api.ts方案1:工程
export const mutateReq = (args: TW): AxiosPromise<TW[]> => {
const query = `
mutation {
update ( id:"${args.id}", name:"${args.name}", iconFile:"${args.iconFile}", elements:[
[
{id:"2",name:"element2",link:"https:",elements:[{id:"1",name:"element1",link:"https://",elements:[]}]}
],
[
{id:"3",name:"element3",link:"https://",elements:[{id:"4", name: "wr", link: "http://", elements: []}]}
],
[]
]){
id
name
iconFile
elements {
id name link
elements {
id name link
}
}
}
}`;
return axios({
url: url,
method: 'post',
headers: {
'Content-Type': 'application/json',
},
data: {
query: query,
},
});
};
GQL查询是一个字符串,当您尝试
元素:${args.elements}
时,它将尝试将对象转换为一个字符串,该字符串很可能类似于[object object]
,但您需要做的是将其转换为JSON字符串,该字符串将为您提供所需的输出
尝试:
这适用于所提出的问题。但是,当我用引号存储key时,它返回了错误(例如:{“elements”:{“id”:“1”})当对…@javascriptnoob进行变异时,您能否澄清使用引号存储密钥的含义?您能否提供代码片段和完整错误?我正在以redux状态存储graphql查询中的数据。我收到的数据存储为{“id”:“1”。…}。在上述变异中,我希望使用我的状态作为参数。但是,因为它是以“”对于键(“id”例如),我不能只使用数据作为突变更新接受id=“1”而不是“id”:“1”。我的错是,您应该实际使用这个:JSON.stringify(obj).replace(/”([^“]+)::/g,$1:”)^这将从所有键中删除引号,尽管它也将从诸如“{”id“:”th\\:ing“}之类的边缘案例中删除引号'因此,请注意不要使用字符串操作/文字,而是使用变量
export const mutateReq = (args: TWorkSpace): AxiosPromise<TWorkSpace[]> => {
const query = `
mutation {
update ( id:"${args.id}" name:"${args.name}" iconFile:"${args.iconFile}" elements:${args.elements}){
id
name
iconFile
elements {
id name link
elements {
id name link
}
}
}
}`;
return axios({
url: url,
method: 'post',
headers: {
'Content-Type': 'application/json',
},
data: {
query: query,
},
});
};
{
id: "1" name: "1" iconFile: "icon.png"
elements: [
[
{id:"2",name:"element2",link:"https://",elements:[{id:"1",name:"element1",link:"https://",elements:[]}]}
],
[
{id:"3",name:"element3",link:"https://",elements:[{id:"4", name: "wr", link: "http:", elements: []}]}
],
[]
]
}
elements:${JSON.stringify(args.elements)}