我正在尝试使用this.props.mutate添加一个用户,但是我收到此错误
TypeError: this.props.mutate is not a function
我以可以调用createUser的方式设置了解析器。但是,我不确定我在做什么错。
我该怎么做才能使反应调用阿波罗突变createUser?
预先感谢
server / resolvers.js
export default {
User: {
posts: (parent, args, context, info) => parent.getPosts()
},
Post: {
user: (parent, args, context, info) => parent.getUser()
},
Query: {
posts: (parent, args, { db }, info) => db.Post.findAll(),
users: (parent, args, { db }, info) => db.User.findAll(),
post: (parent, { id }, { db }, info) => db.Post.findByPk(id),
user: (parent, { id }, { db }, info) => db.User.findByPk(id)
},
Mutation: {
createUser:(parent, {username, email, password}, {db} , info) =>
db.User.create({
username: username,
email: email,
password: password
})
}
};
server / schema.js
export default `
type User {
id: Int!
username: String!
email: String!
password: String!
posts: [Post!]!
}
type Post {
id: Int!
title: String
content: String!
userId: Int!
user: User!
}
type Query {
posts: [Post!]!
post(id: Int!): Post
user(id: Int!): User
users: [User!]!
}
type Mutation {
createPost(title: String, content:String!): Post!
createUser(username: String!, email: String!, password: String!): User!
}
`;
客户端解析器
import { gql } from 'apollo-boost';
const getUsersQuery = gql`
{
users {
id
username
email
password
}
}
`;
const createUserQuery = gql`
mutation createUser($username: String!, $password: String!, $email: String!) {
createUser(username: $username, password: $password, email:$email) {
id
username
email
password
}
}
`;
export {
getUsersQuery,
createUserQuery
}
App.js
import React, {Component} from 'react';
import logo from './logo.svg';
import { Mutation } from "react-apollo";
import './App.css';
import { graphql } from 'react-apollo';
import { getUsersQuery,createUserQuery} from './queries/queries'
class App extends Component{
constructor(props){
super(props);
this.state = {
users: [],
username: '',
password: '',
email: ''
}
}
handleChange = (e) => {
e.preventDefault();
this.setState({
[e.target.name]: e.target.value
})
}
addUser = (e) => {
e.preventDefault()
this.props.mutate({
variables: {
username: this.state.username,
password: this.state.password,
email:this.state.email
}
})
}
componentDidUpdate(nextProps){
if(nextProps.data.users !== this.props.data.users){
this.setState({
users: this.props.data.users
})
}
}
render(){
return(
<div>
owl
<form onSubmit ={this.addUser}>
<input onChange={this.handleChange} type ="text" name="username" value ={this.state.username} placeholder="Enter Username"/>
<input onChange={this.handleChange} type ="text" name="password" value ={this.state.password} placeholder="Enter Password"/>
<input onChange={this.handleChange} type ="text" name="email" value ={this.state.email} placeholder="Enter Email"/>
<button type="submit">Submit</button>
</form>
{this.state.users.map( (user, i) => (
<div key={i}>
<h1>{user.username}</h1>
</div>
))}
</div>
)
}
}
export default graphql(getUsersQuery, createUserQuery) (App);