compose
。然而,由于新版本的react-apollo不再导出它,所以我遇到了错误。我在网上读到,需要将
import { compose } from "react-apollo"
替换为import { compose } from "recompose"
,但是这样做会产生错误TypeError: Cannot read property 'loading' of undefined
。我还读到说应该用import * as compose from "lodash"
替换来自react-apollo的导入,但是当我这样做时,就会出现其他错误,指出× TypeError:lodash__WEBPACK_IMPORTED_MODULE_2__(...)不是一个函数
App.js:import React from "react";
import ApolloClient from "apollo-boost";
import { ApolloProvider } from "react-apollo";
import BookList from "./components/BookList";
import AddBook from "./components/AddBook";
//apollo client setup
const client = new ApolloClient({
uri: "http://localhost:4000/graphql"
});
function App() {
return (
<ApolloProvider client={client}>
<div className="main">
<h1>My Reading List</h1>
<BookList />
<AddBook />
</div>
</ApolloProvider>
);
}
export default App;
queries.js:
import { gql } from "apollo-boost";
const getBooksQuery = gql`
{
books {
name
id
}
}
`;
const getAuthorsQuery = gql`
{
authors {
name
id
}
}
`;
const addBookMutation = gql`
mutation {
addBook(name: "", genre: "", authorId: "") {
name
id
}
}
`;
export { getAuthorsQuery, getBooksQuery, addBookMutation };
AddBooks.js:
import React, { Component } from "react";
import { graphql } from "react-apollo";
import { compose } from "recompose";
// import * as compose from "lodash";
import { getAuthorsQuery, addBookMutation } from "../queries/queries";
class AddBook extends Component {
state = {
name: "",
genre: "",
authorId: ""
};
displayAuthors = () => {
let data = this.props.data;
if (data.loading) {
return <option>loading authors...</option>;
} else {
return data.authors.map(author => {
return (
<option key={author.id} value={author.id}>
{author.name}
</option>
);
});
}
};
submitForm(e) {
e.preventDefault();
console.log(this.state);
}
render() {
return (
<form onSubmit={this.submitForm.bind(this)}>
<div className="field">
<label>Book name: </label>
<input
type="text"
onChange={e => {
this.setState({ name: e.target.value });
}}
/>
</div>
<div className="field">
<label>Genre: </label>
<input
type="text"
onChange={e => {
this.setState({ genre: e.target.value });
}}
/>
</div>
<div className="field">
<label>Author: </label>
<select
onChange={e => {
this.setState({ authorId: e.target.value });
}}
>
<option>Select author</option>
{this.displayAuthors()}
</select>
</div>
<button>+</button>
</form>
);
}
}
export default compose(
graphql(getAuthorsQuery, { name: "getAuthorsQuery" }),
graphql(addBookMutation, { name: "addBookMutation" })
)(AddBook);
我原本期望从react-apollo中导入compose,并将查询和变异使它们在AddBook的props内可用,以便我可以在displayAuthors()和submitForm()函数中使用它们,但实际上我得到了错误提示,称它没有从react-apollo中导出,当我尝试在线找到的建议解决方案时,我遇到了以上提到的其他错误。