我最近完成了一个Reactjs-Graphql教程,该教程未处理错误处理,我一直在尝试自己处理错误,但无法正常工作。
我故意将状态变量初始化为null,因此当我提交一个可以显示给用户的空表格时,我会收到一个错误。
import React, { Component } from "react";
import { graphql } from "react-apollo";
import {
getAuthorsQuery,
addBookMutation,
getBooksQuery
} from "../queries/queries";
import compose from "lodash.flowright";
class AddBook extends Component {
constructor(props) {
super(props);
this.state = {
name: null,
genre: null,
authorId: null
};
}
displayAuthors() {
const { loading, authors } = this.props.getAuthorsQuery;
if (loading) {
return <option disabled>Loading Authors</option>;
} else {
return authors.map(author => {
return (
<option key={author.id} value={author.id}>
{author.name}
</option>
);
});
}
}
submitForm(e) {
e.preventDefault();
const { error } = this.props.addBookMutation;
if (error) {
return error.networkError.result.errors.map(({ message }, i) => (
<span key={i}>{message}</span>
));
} else {
this.props.addBookMutation({
variables: {
name: this.state.name,
genre: this.state.genre,
authorId: this.state.authorId
},
refetchQueries: [{ query: getBooksQuery }]
});
}
}
以下是我的graphql查询:
import { gql } from "apollo-boost";
const getAuthorsQuery = gql`
{
authors {
name
id
}
}
`;
const getBooksQuery = gql`
{
books {
name
id
}
}
`;
const addBookMutation = gql`
mutation($name: String!, $genre: String!, $authorId: ID!) {
addBook(name: $name, genre: $genre, authorId: $authorId) {
name
id
}
}
`;
const getBookQuery = gql`
query($id: ID) {
book(id: $id) {
id
name
genre
author {
id
name
age
books {
name
id
}
}
}
}
`;
这是我尝试提交空白表格时得到的: