我目前正在使用GraphQL研究“CRUD”变异 . 使用Apollo Client和React来控制前端的变异 . 使用Express / mongoose作为后端运行服务器并从本地数据库获取/存储数据 .

使用GraphQL进行工作/测试(中/后端) . 我能够通过localhost:4000 / graphiql工具从本地服务器(mongodb)获取和更改(创建,更新和删除)数据 .

这是突变模式......

const Mutation = new GraphQLObjectType({
    name: 'Mutation',
    fields: {
        addUser: {
            ...
        },
        updateUser: {
            type: UserType,
            args: {
                id: { type: new GraphQLNonNull(GraphQLString) },
                name: { type: new GraphQLNonNull(GraphQLString) },
                age: { type: new GraphQLNonNull(GraphQLInt) }
            },
            resolve(parent, args) {
                let updateIser = User.findByIdAndUpdate(
                    args.id,
                    {
                        $set: { name: args.name, age: args.age }
                    },
                    { new: true }
                ).catch(err => new Error(err));
                return updateUser;
            }
        },
        deleteUser: {
            type: UserType,
            args: { id: { type: new GraphQLNonNull(GraphQLString) } },
            resolve(parent, args) {
                let removeUser = User.findByIdAndRemove(args.id).exec();
                if (!removeUser) {
                    throw new Error('Error, Cannot Delete!');
                }
                return removeUser;
            }
        }
    }
});

现在在使用React和Apollo Client的前端部分,获取数据和渲染迭代贴图是成功的!

enter image description here

我还使用react-router进行页面转换,当点击用户列表中的Add按钮时,它会带我到表单页面填写用户名和年龄 . 完成后,它将提交并重定向(react-router重定向方法)返回到列表页面,其中新创建的用户进入列表(重新获取) . 这个过程对我来说也是成功的!

enter image description here

在更新(编辑)或删除(删除)部分,这是不幸的 . 我面临几个问题......无法更新(编辑)用户

enter image description here

我猜...看起来与点击编辑按钮后无法获取特定ID有关,或者它是否在获取和反应路由器之间存在一些冲突的问题?尽管我试图找到解决方案,但我已经没有想法了 . 所以我希望我可以帮助你解决我面临的问题 .

如果这有帮助......这是名为List.js的React-Apollo语法 - 显示用户列表,包括编辑和删除按钮(尝试失败)

import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import { Link } from 'react-router-dom';
import { getUsersQuery } from '../queries/queries';

class UserList extends Component {

    state = { selected: null };

    displayUser = () => {
        let data = this.props.data;

        if (data.loading) {
            return <div>Loading...</div>;
        } else {
            return data.examples.map(user => (
                <li
                    key={user.id}
                    onClick={e => { this.setState({ selected: user.id });}}
                >
                  {user.name} {user.age}
                    <div className="choices">
                        <Link
                            to="/updateuser"
                            onClick={e => {
                                this.setState({ selected: user.id });
                            }}
                        >
                            <button>Edit</button>
                        </Link>

                        <Link to="/removeuser">
                            <button>Remove</button>
                        </Link>
                    </div>
                </li>
            ));
        }
    };

    render() {
        console.log(this.state.selected);
        return (
            <div id="listContent">
                <h3>List</h3>
                <ul id="userList"> {this.displayUser()}</ul>
                <Link to="/adduser">
                    <button>+</button>
                </Link>
                <div>{this.state.selected}</div>
            </div>
        );
    }
}

export default graphql(getUsersQuery)(UserList);

UpdateForm.js - 呈现更新表单的语法 . 但无法成功改变它 . 可能性问题?

import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import { Redirect, Link } from 'react-router-dom';
import { getUsersQuery, updateUserMutation } from '../queries/queries';

class UpdateUserForm extends Component {
    state = {
        name: '',
        age: '',
        redirect: false
    };

    onChangeName = e => {
        this.setState({ name: e.target.value });
    };

    onChangeAge = e => {
        this.setState({ age: e.target.value });
    };

    onSubmitForm = e => {
        e.preventDefault();
        //console.log(this.state);
        this.props.updateUserMutation({
            variables: {
                id: this.state.id,
                name: this.state.name,
                age: this.state.age
            },
            refetchQueries: [ { query: getUsersQuery } ]
        });
        this.setState({ redirect: true });
    };

    render() {
        const user = this.props.getUsersQuery;

        if (this.state.redirect) {
            return <Redirect to="/" />;
        }
        return (
            <div id="formContainer">
                <form id="form" onSubmit={this.onSubmitForm}>
                    <div className="field">
                        <label>Name:</label>
                        <input
                            type="text"
                            onChange={this.onChangeName}
                            placeholder={user.name}
                        />
                    </div>

                    <div className="field">
                        <label>Age:</label>
                        <input
                            type="text"
                            onChange={this.onChangeAge}
                            placeholder={user.age}
                        />
                    </div>

                    <button>Update</button>
                    <Link to="/">Cancel</Link>
                </form>
            </div>
        );
    }
}

export default compose(
    graphql(getUsersQuery, { name: 'getUsersQuery' }),
    graphql(updateUserMutation, { name: 'updateUserMutation' })
)(UpdateUserForm);

不确定删除页面 - 希望只需点击删除按钮,从列表页面将获取特定ID和变异(删除)用户 .

这是名为queries.js的Apollo Client查询代码 .

// Fetch Users
const getUsersQuery = gql`
    {
        users {
            name
            age
            id
        }
    }
`;

// Update User Mutation
const updateUserMutation = gql`
    mutation($id: ID!, $name: String!, $age: Int!) {
        updateUser(id: $id, name: $name, age: $age) {
            id
            name
            age
        }
    }
`;

// Remove User Mutation
const removeUserMutation = gql`
    mutation($id: ID!) {
        deleteUser(id: $id) {
            id
        }
    }
`;

提前致谢...