登录状态不会在 React、Apollo Client 2、Graphcool 中反应性更新

Logged in state doesn't reactively update in React, Apollo Client 2, Graphcool

我正在使用 React、Apollo Client 2 和 Graphcool。我实现了一个登录表单。在登录页面上,根据客户端登录的天气情况,会显示登录表单或注销按钮。

我的代码可以工作,但不会响应式更新。用户登录或注销后,在刷新页面之前不会发生任何变化。如何使我的代码具有反应性?

import React from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';

class Login extends React.Component {
    constructor(props) {
        super(props);
        this._confirm = this._confirm.bind(this);
    }

    _confirm = async e => {
        e.preventDefault();

        const result = await this.props.LoginMutation({
            variables: {
                email: '5@gmail.com',
                password: 'password',
            },
        });

        const token = result.data.authenticateUser.token;
        this._saveUserData(token);
    };

    _saveUserData = token => {
        localStorage.setItem('auth-token', token);
    };

    render() {
        return (
            <div>
                {this.props.LoginQuery.user ? (
                    <button onClick={() => localStorage.removeItem('auth-token')}>
                        Logout
                    </button>
                ) : (
                    <form onSubmit={this._confirm}>
                        <input type="email" id="email" />
                        <input type="password" id="password" />
                        <button type="submit">Login</button>
                    </form>
                )}
            </div>
        );
    }
}

const LoginMutation = gql`
    mutation authenticateUser($email: String!, $password: String!) {
        authenticateUser(email: $email, password: $password) {
            token
        }
    }
`;

const LoginQuery = gql`
    query AppQuery {
        user {
            id
        }
    }
`;

const LoginContainer = compose(
    graphql(LoginMutation, { name: 'LoginMutation' }),
    graphql(LoginQuery, { name: 'LoginQuery' }),
)(Login);

export default LoginContainer;

任何与 UI 有关的内容都不一定需要保护。因此,您可以轻松地使用状态或数据存储(例如 redux、mobx 等)来触发对 UI.

的更新

如果您想根据使用 GraphQL 的突变对 UI 进行反应性更新。老实说,我建议实施订阅,这将为您提供您正在寻找的那种反应性数据流。

Subscriptions ~ Apollo Client