我正在使用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;发布于 2018-01-29 02:43:28
任何涉及UI的东西都不一定需要保护。因此,您可以轻松地只使用状态或数据存储(如redux、mobx等)。触发对UI的更新。
如果您希望基于GraphQL的突变对UI进行响应式更新。老实说,我建议实现订阅,它将为您提供您正在寻找的那种反应式数据流。
https://stackoverflow.com/questions/48486225
复制相似问题