我已将所有查询存储在其页面上:
import gql from "graphql-tag";
const getStories = gql`
query getStories {
stories {
id
title
author
tagline
summary
rating
you
need
go
search
find
take
returned
changed
}
}
`
const createStory = gql`
mutation($title: String!, $author: String!) {
create (title: $title, author: $author) {
id
title
author
tagline
summary
rating
you
need
go
search
find
take
returned
changed
}
}
`
const updateStory = gql`
mutation($id: ID!) {
update(id: $id) {
id
title
author
tagline
summary
rating
you
need
go
search
find
take
returned
changed
}
}
`
export default { getStories, updateStory, createStory };
在我的表单页面上,我导入了createStory突变,并试图将其与Component绑定,如下所示:
import React, { Component } from "react"
import { withRouter } from 'react-router-dom'
import graphql from 'graphql-tag'
import createStory from '../../Queries/Queries'
class Form extends Component {
constructor(props) {
super(props);
this.state = {
story: {}
};
}
onChange = e => {
const storyState = this.state.story;
storyState[e.target.name] = e.target.value;
console.log(this.props.createStory)
console.log(storyState)
this.setState(storyState);
};
onSubmit = e => {
e.preventDefault();
console.log(this.state.story)
this.props.createStory({
variables: {
story: this.state.story
}
})
this.props.history.replace('/')
};
render() {
return (
<div className="card">
<h1>Write A Story</h1>
<form onSubmit={this.onSubmit}>
// Cut out my form details for space
<input type="submit" value="Write Story" />
</form>
</div>
);
}
}
const createStoryMutation = graphql(createStory, {
name: 'createStory'})(Form)
export default withRouter(createStoryMutation)
但是,我一直在运行中收到错误消息。
GraphQLError: Syntax Error: Unexpected Name "undefined"
起初,我怀疑这是一个包装问题,所以我一直试图解决的方法之一是在graphql-tag
和react-apollo
之间进行交替。但是,当与这些混乱时,我会不断得到Object(...) is not a function
,我知道这与是否将导入的函数包装在{brackets}中有关。
为了使此代码正常工作,我几乎尝试了所有我知道的事情,但没有成功。我知道我的发布突变也很长(也就是应该包装在一个输入对象中),但是我只是想在清理之前使事情起作用。
话虽这么说,谢谢你。
答案 0 :(得分:3)
请注意,您正在表单组件文件顶部执行import graphql from 'graphql-tag'
。我猜想您实际上是根据您在发布的代码中将import { graphql } from 'react-apollo';
用作HOC的方式来尝试做graphql
。
您的导入/导出也不正确。您不应该具有默认导出功能,而应将export
关键字放在每个查询定义的前面。然后,您需要将import createStory from '../../Queries/Queries'
更改为import {createStory} from '../../Queries/Queries'
。当前,您将createStory
设置为等于{ getStories, updateStory, createStory }
。
答案 1 :(得分:1)
在合并堆栈(https://www.youtube.com/watch?v=C_2Eo72cL2k)上跟随youtube项目时,我遇到了类似的错误。对我来说,问题是我没有在查询前添加“查询”,也没有将其用大括号括起来。这样做都会导致错误消失,但是前者会导致控制台中出现400错误的请求错误。