首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在React、Apollo Client 2、Graphcool中登录状态没有反应更新

在React、Apollo Client 2、Graphcool中登录状态没有反应更新
EN

Stack Overflow用户
提问于 2018-01-28 20:13:23
回答 1查看 146关注 0票数 0

我正在使用React,Apollo Client 2和Graphcool。我已经实现了一个登录表单。在登录页面上,根据客户端是否登录而显示登录表单或注销按钮。

我的代码可以工作,但不会进行反应性更新。用户登录或注销后,在刷新页面之前不会发生任何更改。怎样才能使我的代码成为响应式的?

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-29 02:43:28

任何涉及UI的东西都不一定需要保护。因此,您可以轻松地只使用状态或数据存储(如redux、mobx等)。触发对UI的更新。

如果您希望基于GraphQL的突变对UI进行响应式更新。老实说,我建议实现订阅,它将为您提供您正在寻找的那种反应式数据流。

Subscriptions ~ Apollo Client

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48486225

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档